0

* 入力スキャンの修正
Enter キー/空白行を使用して while ループを終了しようとしています 以下のテスト コードは正常に動作します。

    Scanner scan = new Scanner(System.in);
    String line;

    while ( (line=scan.nextLine()).length() > 0)  
    {
        System.out.println(line);
    }

ただし、メインプログラム内に統合すると (do-while ループ内の int スイッチケース内に配置された while ループ)、プログラムはコード @case2 をスキップし、do-while ループを続行します

int input;
do{
      System.out.print("Choose a function (-1 to exit): ");
      input=scan.nextInt();
      switch (input)
      {
          case 1:
          break;
          case 2:
          //same while loop here
          break;
      }

  }while(input!=-1);

出力例:

Choose a function (-1 to exit): 1
Choose a function (-1 to exit): 2
//skip case2 coding
Choose a function (-1 to exit): 1
Choose a function (-1 to exit): -1
//program ends
4

3 に答える 3

0

助けてくれてありがとう!いくつかの試行錯誤の後、コードが機能するようになりました

Scanner scan = new Scanner(System.in);
  int input;
  do{
  System.out.print("Choose a function (-1 to exit): ");
  input=scan.nextInt();       

  switch (input)
  {
  case 1:
     break;
  case 2:
     System.out.println("..2"); 
     String line;
     scan.nextLine();//skips the entire current line.
     while ( (line=scan.nextLine()).length() > 0)  
        {
        System.out.println(line);
        }
        break;
     }
  }while(input!=-1);    

System.out.println() は scan.nextInt() から
の干渉をクリアしているようですが、私の理論にすぎません

于 2015-06-20T12:58:04.563 に答える
0

100% 確実ではありませんが、スキャナーがすべての入力を読み取っていないと思います。スキャナが読み取りを開始したときにバッファに空白行 (改行文字) があるため、空の行が返され、行の長さが 0 になり、すぐにループが終了します。

あなたの現在のプログラムが何であるかについての私の最善の推測は次のとおりです。

public class InputTest
{

   public static void main( String[] args )
   {
      Scanner scan = new Scanner( System.in );
      int input = 0;
      do {
         System.out.print( "Choose a function (-1 to exit): " );
         input = scan.nextInt();
         switch( input ) {
            case 1:
               System.out.println("..1");
               break;
            case 2:
               System.out.println("..2");
               //same while loop here
               String line = scan.nextLine();
               System.out.println(">>"+line+"<<");
               while( line.length() > 0 ) {
                  System.out.println( "  Read line: " + line );
                  line = scan.nextLine();
                  System.out.println(">>"+line+"<<");
               }
               break;
         }
      } while( input != -1 );
   }
}

そしてその出力:

run:
Choose a function (-1 to exit): 1
..1
Choose a function (-1 to exit): 2
..2
>><<
Choose a function (-1 to exit): -1
BUILD SUCCESSFUL (total time: 11 seconds)

>><<読み取られたが空であることを意味する行が出力されていることがわかります。改行は数字の 2 の一部ではなく、バッファに残されるため、上記の「2」の残りの改行だと思います。

于 2015-06-20T02:58:41.860 に答える