0

How to add up different strings in a loop?

My Example:

Having a Stern–Brocot tree path finder. The only problem is that it should give output as one line. Full code:

import java.io.*;
import java.util.*;
public class Main {
  public static void main(String[] args) {
    double p, q;
    Scanner in = new Scanner(System.in);
    int[] vars = new int[2];
    for(int i = 0; i < vars.length; i++)
      vars[i] = in.nextInt();
    p = vars[0];
    q = vars[1];

  double p1 = 0 ;
  double p2 = 1 ;

  double q1 = 1 ;
  double q2 = 0 ;
  while( p1+p2 != p  && q1+q2 != q )
  {
      if (( p1+p2 )/ (q1+q2 ) < p / q) 
      {
          System.out.println("R");
          p1 += p2;
          q1 += q2;
      } 
      else if( ( p1+p2 ) / ( q1+q2 ) > p/q )
      {
          System.out.println("L");
          p2 += p1;
          q2 += q1;
      }
    }
  }
}

The main part. The part i have to fix.

while( p1+p2 != p  && q1+q2 != q )
  {
      if (( p1+p2 )/ (q1+q2 ) < p / q) 
      {
          System.out.println("R");
          p1 += p2;
          q1 += q2;
      } 
      else if( ( p1+p2 ) / ( q1+q2 ) > p/q )
      {
          System.out.println("L");
          p2 += p1;
          q2 += q1;
      }
    }
  }

Problem: How could i make it like that, that each time it does the loop, it will add the answer to the full answer and after everything is done, it throws full answer in one line. Pretty much something like that:

answer = answer + ("R");
answer = answer + ("L");
System.out.println(answer);
0

3 Answers 3

1

Using System.out.print() instead of System.out.println() would work here, I guess.

Sign up to request clarification or add additional context in comments.

Comments

1

Use StringBuilder.

Make an instance of StringBuilder before the loop, and call append method repeatedly to construct the output string. Once you are done forming the result string, call toString to obtain and print the final result.

StringBuilder answerBuilder = new StringBuilder();
while( ... ) {
    ...
    answerBuilder.append("L");
    ...
    answerBuilder.append("R");
    ...
}
String answer = answerBuilder.toString();

An advantage of keeping a StringBuilder over printing-as-you-go approach is that you can go back and change the beginning or the middle of the string that you build before printing it.

Comments

1

If you want the answer at the last just use StringBuilder and append each string you display and at the end just show this StrigBuilder variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.