2016-10-12 10 views
0

満足していないにもかかわらず、私のループしたエラーメッセージをプリントアウトしここに私のコードのスニップです:はなぜループ内で設定された条件が

while (true){ 
     System.out.println("---Welcome to the Shape Machine---"); 
     System.out.println("Available options:"); 
     System.out.println("Circles"); 
     System.out.println("Rectangles"); 
     System.out.println("Triangles"); 
     System.out.println("Exit"); 
     //asks for selection 
     String option = console.next(); 

     while (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){ 
      System.out.println("#ERROR Invalid option. Please try again."); 
      break; 
      } 

     switch (option) { 

     case "Circles": { 

私はセットアップメニューを持っており、ユーザーがイマイチ何を入力するとオプションの1つは、エラーメッセージを表示して、ユーザーをメニューに戻します。これは意図したとおりに動作しますが、正しい入力を入力すると、エラーメッセージが表示されますが、switch文はエラーがないかのように実行され、必要な計算が行われます。私はif else文の中で真のループを使用しようとしましたが、私はまだ同じ問題を抱えていました。また、!()。equalsメソッドの代わりに!=を使用して、AND演算子の代わりにOR演算子を使用してみました。私はそれを修正するために何をすべきか分かりません。どんな助けも非常に高く評価されるでしょう。

+2

あなたの 'while'は、無条件の' break'のために 'if'です。そして、もちろん、「スイッチ」は常に実行されます、それはあなたがするように言ったものです。私はあなたが 'break'の代わりに' continue outerLoop'を望んだと思います。 –

+0

ようこそスタックオーバーフロー、[MCVE](http://stackoverflow.com/help/mcve)を投稿することを検討してください。 – Athamas

答えて

1

私はここで野生の推測に行き、あなたが達成しようとしていたものを理解しようとします。

while (true){ 

     System.out.println("---Welcome to the Shape Machine---"); 
     System.out.println("Available options:"); 
     System.out.println("Circles"); 
     System.out.println("Rectangles"); 
     System.out.println("Triangles"); 
     System.out.println("Exit"); 
     //asks for selection 
     String option = console.next(); 

     switch (option) { 

     case "Circles": 
      //do something 
       break; 
     case "Rectangles": 
       break; 
     case "Triangles": 
       break; 
     case "Exit": 
       break; 
     default: 
       System.err.println("#ERROR Invalid option. Please try again."); 

     } 
    //now you can either put a flag or change the code to a DO..While 
    //depending on if you want to re-execute after each option.. 

} 

あなたが声明、あなたがしている場合つもりたくは(あなたのバージョンに従うこと)を行う場合:

これを試してみて読みやすくするために、

if (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){ 
    //print the error, then continue 
} 

または

if(! ((option.equals("Circles") || option.equals("Rectangles") || option.equals("Triangles") || option.equals("Exit"))){ 
    //print the error, then continue 
} 

また、正しい値を読んでいることを確認し、印刷して確認してください。

これが機能しない場合は、提供していないコードにエラーがある必要があります。その場合は、MCVEを送信してください。

+1

私はブレークが本当に何をしているのか、if文としてwhileループを使っていたのか分からなかったと思います。何が間違っていたかを理解しようと時間を費やしていましたが、皆分かったことがあります。ありがとうございました。 –

関連する問題