0

This is the code:

public class Pr3 
{
  public Pr3 ()
  {
    String x = "";
    String Line = "";
    Scanner sc = new Scanner (System.in);
    do 
    {
        System.out.println ("Please enter your sentence");
        String NewLine = sc.nextLine();
        Line = Line + " " + NewLine;
        System.out.println ("Your new Line is: " + Line); 
        System.out.println ("Do you want to enter a new sentence? Enter Y for yes and N for no");
        x = sc.next();
    } while (!"N".equals(x) && "Y".equals(x));
    exit(0);
   }
 }

And this is the output:

  • Please enter your sentence
  • Hagar
  • Your new Line is: Hagar
  • Do you want to enter a new sentence? Enter Y for yes and N for no
  • Y
  • Please enter your sentence
  • Your new Line is: Hagar
  • Do you want to enter a new sentence? Enter Y for yes and N for no
rkachach
  • 13,862
  • 5
  • 35
  • 55
TheGrimBoo
  • 179
  • 1
  • 2
  • 13

1 Answers1

1

Change

x = sc.next();

to

x = sc.nextLine();

in order to consume the end of line characters.

Beside that,

Line = Line + " " + NewLine;

will concatenate the new line to all the previous lines. I'm not sure that's what you want (based on your printing of System.out.println ("Your new Line is: " + Line);).

One last thing :

while (!"N".equals(x) && "Y".equals(x));

is redundant. If x is equal to "Y", it's not equal to "N", so it's enough to write :

while ("Y".equals(x));
Eran
  • 359,724
  • 45
  • 626
  • 694