0

So the loop works but I have to press enter twice for it to print out the next input, I know it's with my loop and I know it's because the new input is set after the method scanz but I can't put it before/ eliminate it outside the loop because then the creation of the object Scanning doesn't work. Help is appreciated!

public class NumberScanned {

    public static void main(String[] args) {
        System.out.println("Please enter '.' when you want to terminate");
        Scanner keyboard = new Scanner(System.in);
        String scannedString=keyboard.nextLine();
        Scanning scanz= new Scanning(scannedString);

    do 
    {

        System.out.println("Numbers: "+scannedString); 

       scanz.set(scannedString);

       scanz.printState();

   scannedString=keyboard.nextLine();

 }
 while(!keyboard.nextLine().equals("."));

        keyboard.close();


    }
}
4

1 回答 1

0

将循环更改为以下模式:

   String scannedString = keyboard.nextLine();
    do {
        System.out.println("Numbers: "+scannedString); 
        scanz.set(scannedString);
        scanz.printState();
    } while (!(scannedString = keyboard.nextLine()).equals("."));

这种方式条件检查与读取新行一起完成。还有更易读的方法:

    String scannedString = null;
    while (!(scannedString = keyboard.nextLine()).equals(".")) {
        System.out.println("Numbers: "+scannedString); 
        scanz.set(scannedString);
        scanz.printState();
    }
于 2013-08-29T18:20:23.157 回答