0

I am currently trying to have a recurring loop where the user inputs values to add to a linked list. But every time there is a space within one of the input values it causes the loop to skip the flag nextLine() input.

Here is the code:

while(true)
        {
            
            System.out.println("Please enter product name: ");
            productName = input.nextLine();

            
            System.out.println("Please enter the Price: ");
            price = input.nextDouble();
        
            productList.addProduct(productName, price);
        
            System.out.println("Are you done with this transaction? Y/N: ");
            stopFlag = input.nextLine();
            
            if(stopFlag.equalsIgnoreCase("y"))
                break;
        }

If I input "villainous" as the first string and then 22.99 as the double value it works fine. Then I can input either y/n to exit. But! if I say input "Villainous exp" as the first string, the second double input works fine, then the last one skips and I get an output like:

Please enter product name:

Villainous Exp

Please enter the Price:

22.99

Are you done with this transaction? Y/N:

Please enter product name:

I don't know how to make it not skip the bottom input or understand why it is even doing so.

1 Answers1

-1
import java.util.*;

public class Main
{



  public static void main (String[]args)
  {
    Scanner input = new Scanner (System.in);
    boolean flag=false; int no=1; 
    for (int i=0;i<no && flag==false;i++)
      {

    System.out.println ("Please enter product name: ");
    String productName = input.nextLine ();
    System.out.println ("Please enter the Price: ");
    Double price = input.nextDouble ();

    // productList.addProduct(productName, price);

      System.out.println ("Are you done with this transaction? Y/N: ");
    char c = input.next (".").charAt (0);

    if (c == 'y')
      {
        System.out.println ("OK ");
            System.out.println ("Entry Saved! ");
            flag=true; 
      }
    else {
        no++;
    }
        input.nextLine(); 

      }
  }}

Edit: the program should work now. The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present.

Read more about it at https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/

Hana H.
  • 1
  • 2