2017-11-23 18 views
0

私は現在、小学生のための数学ゲームを開発しています。私は、正しい質問を得るまで、ユーザーが継続的に回答を入力できるようにしています。その後、私は彼らに次の質問に移ります。下のコードを実行すると、正解を入力するチャンスは2回与えられますが、2回目以降は「正解」というメッセージが表示されません。正しい入力が入力されるまでスキャナが入力を要求し続けるようにする方法はありますか? Java

import java.util.Scanner; 
public class test{ 
    public static void main (String[]args){ 
     Scanner kb= new Scanner(System.in); 
     double r5q1,r5q2,r5q3,r5q4,r5q5; 
     System.out.println("Welcome to the money level.. This is the last and most difficult level!"); 
     //Question 1 
     System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?"); 
     r5q1=kb.nextDouble(); 

     if(r5q1==7) 
      System.out.println("Correct!"); 
     else 
      System.out.println("Try again!"); 
      r5q1=kb.nextDouble(); 
    } 
} 

This is a photo of my code

答えて

0

内のコードを取って、あなたの入力を入れてループと中ながら、正しい出力のための条件チェック

do{ 
    statements(s) 
}while(condition); 
0

はこれを試すながら行います。あなたは、whileループを使用する必要が

import java.util.Scanner; 

public class Main 
{ 
    public static void main (String[] args) 
    { 
     Scanner cin = new Scanner(System.in); 
     int ans = 123; 
     do { 
      System.out.println("Your question here.\n"); 
     } while (cin.nextInt() != ans); 
     System.out.println("correct!\n"); 
    } 
} 
0
while(userAnswer != realAnswer){ 
    System.out.print("Wrong answer. Try again: "); 
    userAnswer = in.nextInt(); // or whatever you need instead of int 
} 
0

。このループは、条件(中括弧内のブール値)が真である間に、その "内容"(中括弧内のコード)を繰り返します。この場合、入力はであり、「内容」は「もう一度お試しください!」というコードです。メッセージ。 ここにデモがあります:

Scanner scanner = new Scanner(System.in); 
while (scanner.nextDouble() != 7) { 
    System.out.println("Try again!"); 
} 
System.out.println("Correct!"); 
0

フラグ値を宣言します。そして、最初にそれを0に設定します。

do{ 
    if(r5q1==7){ 
    flag=1; 
    break; 
    } 
    else{ 
    continue; 
     } 
    }while(r5q1!=7); 

    if(flag==1) 
    { 
    System.out.println("Correct"); 
    } 
    else 
    { 
    System.out.println("Wrong"); 
    } 
0

ありがとうございました!それはとてもうまくいった!

import java.util.Scanner; 
public class test{ 
    public static void main (String[]args){ 
     Scanner kb= new Scanner(System.in); 
     double r5q1,r5q2,r5q3,r5q4,r5q5; 
     System.out.println("Welcome to the money level.. This is the last and most difficult level!"); 
     //Question 1 
     System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?"); 
     r5q1=kb.nextDouble(); 
     do{ 
      System.out.println("Try again!"); 
      r5q1=kb.nextDouble(); 
     }while(r5q1!=7);//This is the answer to the question 
     System.out.println("Correct!"); 

     //Question 2 
     System.out.println("Question 2: I have $15.00 and I buy 5 apples for $1.00 each. How much change will I get?"); 
     r5q1=kb.nextDouble(); 
     do{ 
      System.out.println("Try again!"); 
      r5q2=kb.nextDouble(); 
     }while(r5q2!=10); //This is the answer to the question 
     System.out.println("Correct!"); 
    } 
} 
関連する問題