|
-
Nov 26th, 2002, 02:41 PM
#1
Thread Starter
New Member
how do i loop a answer ????
hi how do i loop my code below, so that when a wrong answer is entered it will loop back and keep asking the same question till it is answered right.
import java.io.*;
class School2
{
public static void main (String[]args) throws IOException
{
int answer;
int total;
int No1;
int No2;
No1 =1+(int) (Math.random()*10);
No2 =1+(int) (Math.random()*10);
total=No1*No2;
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
{
System.out.println("Mulitply "+ No1+" by "+ No2);
line = input.readLine();
answer = Integer.parseInt(line);
if (answer == total)
System.out.println("Well Done the answer was "+" "+total);
else
if (answer != total)
System.out.println("Sorry try again");
}
}
}
thanks if you can help
-
Nov 26th, 2002, 06:18 PM
#2
First of all: use code tags to preserve your indenting. The code you posted is very hard to read because all indenting is lost.
Second:
Code:
import java.io.*;
class School2
{
public static void main (String[]args) throws IOException
{
int answer;
int total;
int No1;
int No2;
No1 =1+(int) (Math.random()*10);
No2 =1+(int) (Math.random()*10);
total=No1*No2;
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Mulitply "+ No1+" by "+ No2);
while(true) {
line = input.readLine();
try {
answer = Integer.parseInt(line);
} catch(NumberFormatException e) {
System.out.println("Please enter a valid number.");
continue;
}
if (answer == total) {
System.out.println("Well Done the answer was "+" "+total);
break;
} else
System.out.println("Sorry try again");
}
}
}
Added the while loop, a try-catch block in case the user doesn't even enter a number and removed an redundant if.
On a side note: when the user enters the correct answer the computer replys with
"Well Done the answer was [real answer]"
Since the user just entered the correct answer, does it make sense to output it again?
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|