2017-04-20 15 views
-3

私の割り当てのためのプログラムを作成しています。これはプログラム全体ではありませんが、その一部に過ぎません。Javaでのwhileループの終了

"items"配列に格納する整数値を入力する必要があります。ユーザーが "stop"を入力すると、ループが終了し、ここで問題が発生します。プログラムを停止すると、プログラムが停止してエラーが表示されます。

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i=0, lines=1; 
    int[] items = new int[100]; 
    int total = 0; 
    System.out.println("Enter the items with its price"); 

    while(true){ 
      i=i+1; 
      if ("stop".equals(scan.nextLine())) 
       break; 
      else 
       items[i] = scan.nextInt(); 
    } 

} 
+3

エラーは何ですか?それはかなり重要です – Carcigenicate

+0

"いくつかのエラー" - あなたの質問にこれらのエラーを含める価値があります。 – px06

+0

これで、スレッド "main"の例外java.util.InputMismatchException \t(java.util.Scanner.java:864) \t(java.util.Scanner.java:1485) java.util.Scanner.nextInt(Scanner.java:2117)java.util.Scanner.nextIntで \t(Scanner.java:2076)mohammedkabbani_301502670.MohammedKabbani_301502670.mainで \t(MohammedKabbani_301502670.java:34) で\t C:¥Users¥Mohammed¥AppData¥Local¥NetBeans¥Cache¥8.2¥executor-snippets¥run.xml:53:Java戻り値:1 BUILD FAILED(合計時間:8秒) – Mick2160

答えて

1

あり、特定のミスをe。エラーを追加するだけの方が良いでしょう。

このコードを試してください。他の回答の上に

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i = 0, lines = 1; 
    int[] items = new int[100]; 
    int total = 0; 
    System.out.println("Enter the items with its price"); 

    while(true){ 
      String InputTxt = scan.nextLine(); 
      if (InputTxt.equals("stop")) 
       break; 
      else{   
       try{ 
       items[i] = Integer.parseInt(InputTxt); 
       i++; 
       }catch(Exception e){ 
       System.out.println("Please enter a number"); 
       } 
      } 

    } 

} 
-1

あなたの問題は、この行です:あなたが入力した文字列stopている間の整数を取得しようとしているので、items[i] = scan.nextInt();

EDIT 一つの可能​​な解決策は、あなたが文字列としてデータを取得し、それかどうかを確認ということですstopかではなく、その後、解析しようとしていない場合には、怒鳴るようなコード整数に:あなたのタラで

public static void main(String[] args) { 

Scanner scan = new Scanner(System.in); 
int i=0, lines=1; 
int[] items = new int[100]; 
int total = 0; 
System.out.println("Enter the items with its price"); 
while(true) 
    { 
    i=i+1; 
    String str = scan.nextLine() 
    if ("stop".equals(str)) 
     break; 
    else 
     { 
     items[i] = Integer.parseInt(str) 
     } 
    } 
} 
+0

さて、どうすればいいですか?私はユーザーから整数を入力したいと思います。整数を書き終えたら、プログラムを終了するために書き留めてください。 – Mick2160

+0

私は 'scan.nextLine()'がその段階で何かを読むので、これは問題ではないと考えています。これは変換に問題がある 'NumberFormatException'ではありません。 – px06

+0

@ px06あなたは 'scan.nextLine()'についてあなたは正しいですが、コード中に 'items [i] = scan.nextInt();'という別の行があるので、それは整数として入力を取得しようとします。 – pooyan

0

、私はこのアプローチを使用

//first you need to remove the local variable i 
for(int i = 0; i < items.length; ++i) 

while(true) 

からループに変更することをアドバイスしたいはIndexOutOfBoundsExceptionを避けるために役立ちますユーザーが100以上の整数値をキー入力したとき。

関連する問題