I am trying to output the amount of test scores between 5 and 35. I do get an invalid entry when the integer entered is below 5 or above 35, which is required. However, when I enter a number between 5 and 35, nothing happens. I get a blank line. The only way I can get "Enter Score" to show up is when I enter another number and press "Enter/Return". What am I doing wrong?
Here is my code:
============================
import java.text.NumberFormat;
import java.util.Scanner;
public class ValidatedTestScoreApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int maximumScore = 0;
int minimumScore = 100;
// get the number of scores to be entered
int amtTest = getIntWithinRange(sc,"Enter the number of test scores to be entered: ", 5, 35);
int numberOfEntries = sc.nextInt();
System.out.println();
sc.nextLine();
for (int i = 1; i <= numberOfEntries; i++)
{
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
maximumScore = Math.max(maximumScore, testScore);
minimumScore = Math.min(minimumScore, testScore);
}
else if (testScore != 999)
{
System.out.println("Invalid entry, not counted");
i--;
}
}
// calculate the average score
double averageScore = (double) scoreTotal / (double) scoreCount;
// display the results
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + number.format(averageScore) + "\n"
+ "Minimum score: " + minimumScore + "\n"
+ "Maximum score: " + maximumScore + "\n";
System.out.println(message);
// see if the user wants to enter more test scores
System.out.print("Enter more test scores? (y/n): ");
choice = sc.next();
System.out.println();
}
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
}
The problem is that you are trying to read the values multiple times.
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
Here you already got the value from the getIntWithinRangeMethod, but on the next line you are reading it again.
Also what are the amtTest and testScores variables good for? I'm not sure what you are trying to accomplish, but I guess you need to do these two changes:
// get the number of scores to be entered
// int amtTest = getIntWithinRange(sc, "Enter the number of test scores to be entered: ", 5, 35);
// int numberOfEntries = sc.nextInt();
int numberOfEntries = getInt(sc, "Enter the number of test scores to be entered: ");
// System.out.println();
// sc.nextLine();
...
// int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
After this, the programs behaves fine and I get this:
Enter the number of test scores to be entered: 2
Enter score 1: 5
Enter score 2: 6
Score count: 2
Score total: 11
Average score: 5.5
Minimum score: 5
Maximum score: 6
Enter more test scores? (y/n):
Related
I need to do Football Results Generator. I created 4 arrays with 10 elements each, but I need to include a loop that allows the user to change their mind and stop input by typing "quit" after a certain number of entries. Could you please help - I am new to programming, so it must be dead simple.
import java.util.Scanner;//
public class Football_Results_Generator
{
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
String[] HomeTeam = new String[10];
String[] AwayTeam = new String[10];
int[] HomeScore = new int[10];
int[] AwayScore = new int[10];
int index = 0;
int sum = 0;
int sum1 = 0;
do
{
System.out.print("Enter Home Team Name: ");
HomeTeam[index] = kbd.nextLine();
System.out.print("Enter Away Team Name: ");
AwayTeam[index] = kbd.nextLine();
System.out.print("Enter Home Team Score:");
HomeScore[index] = kbd.nextInt();
System.out.print("Enter Away Team Score: ");
AwayScore[index] = kbd.nextInt();
kbd.nextLine();
} while(index < 10);
index = 0;
System.out.println();
do
{
System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
index = index + 1;
} while(index < 10);
kbd.close();
for(index = 0; index < 10; index++)
sum += HomeScore[index];
for(index = 0; index < 10; index++)
sum1 += AwayScore[index];
System.out.println();
System.out.println("Totals");
System.out.println("-------------------------------");
System.out.println("Total number of matches played: " + index);
System.out.println("Total of all home scores: " + sum);
System.out.println("Total of all away scores: " + sum1);
System.out.println("Total number of draws: ");
System.out.println("The highest home score: ");
System.out.println("The highest away score: ");
}
}
allow user to change his mind and stop input by typing quit after 5 tries.
Use a temp variable to capture String input:
String line;
do
{
System.out.print("Enter Home Team Name: ");
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
HomeTeam[index] = line;
.....
index = index + 1; //missed
}while(index < 10);
index = 0;
Here, "quit".equalsIgnoreCase(line) will ensure that irrespctive of case of line e.g. "Quit","QUIT","quit",etc will result true
What about integer input to array?? is it same concept ??
Well, you need to handle the exception in case input is neither quit nor int:
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
try{
HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
//Error conversion string to int
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
import java.util.Scanner;
public class OnlineTest {
public static void entry() {
Scanner input = new Scanner(System.in);
System.out.println("Please, Enter Your Full Name :");
String name = input.nextLine();
System.out.println("Please, Enter your Test Registration ID :");
double id = input.nextDouble();
System.out.println(" . . . Starting Test\n");
test(double score1, double score2, double score3);
}
public static void test(double score1, double score2, double score3) {
String answer;
Scanner input = new Scanner(System.in);
System.out.println("- Choose the Correct Answer:\n");
do {
System.out.println("a. Which Utility is used to compile Java applications?\n"
+ " 1. javaw\n"
+ " 2. java\n"
+ " 3. javac " );
answer = input.next();
}while(!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if(answer.equals("3") ) {
score1 = 100;
}else if (!answer.equals("3")) {
score1 = 0;
}
do {
System.out.println("b. Which is a restriction when using a switch statement? \n"
+ " 1. Characters cannot be used\n"
+ " 2. Doubles cannot be used\n"
+ " 3. Integers can not be used" );
answer = input.next();
}while(!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if(answer.equals("1") ) {
score2 = 100;
}else if (!answer.equals("1")) {
score2 = 0;
}
do {
System.out.println("c. What is the range of byte data type in Java? \n"
+ " 1. -128 to 127\n"
+ " 2. -32768 to 32767\n"
+ " 3. -2147483648 to 2147483647" );
answer = input.next();
}while(!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if(answer.equals("1") ) {
score3 = 100;
}else if (!answer.equals("1")) {
score3 = 0;
}
double totalscores = score1 + score2 + score3;
}
public static void results(double totalscores) {
double percentage = totalscores ;
printData(percentage);
}
public static void printData(double percentage) {
System.out.println("-----------------------");
System.out.println("\tJava Certification\n"
+ "\t Test Results\n");
System.out.println("Name : " );
System.out.println("Passing Score 52% ");
System.out.println("Your Score : " + percentage + "% \n");
System.out.println("Max Score --------------------100%\r\n" +
"Passing Score -----------52");
}
public static void main(String[] args) {
entry();
printData(double percentage);
}
}
important file final project
How can I solve it about online test to be like in the pdf file?
Hi!This is your code without errors!
So, I changed somethings, I'll list them to get clearer.
To use "Name" and "Id" in more than one method, it is easier if they are global variables.
When calling the "test" method you need to pass the values, so in the "entry" method the values are passed.
The "printData" method is called within "results" to receive the value of "totalScores"
Also in the "results" method to calculate the value of "percentage" you must divide by the number of scores, which in this case is 3
The methods need to be static, just the test method. In the test method, a class must be instantiated to test the class itself.
import java.util.Scanner;
public class OnlineTest {
String name;
double id;
public void entry() {
Scanner input = new Scanner(System.in);
System.out.println("Please, Enter Your Full Name :");
name = input.nextLine();
System.out.println("Please, Enter your Test Registration ID :");
id = input.nextDouble();
System.out.println(" . . . Starting Test\n");
test(0, 0, 0);
}
public void test(double score1, double score2, double score3) {
String answer;
Scanner input = new Scanner(System.in);
System.out.println("- Choose the Correct Answer:\n");
do {
System.out.println("a. Which Utility is used to compile Java applications?\n" + " 1. javaw\n"
+ " 2. java\n" + " 3. javac ");
answer = input.next();
} while (!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if (answer.equals("3")) {
score1 = 100;
} else if (!answer.equals("3")) {
score1 = 0;
}
do {
System.out.println(
"b. Which is a restriction when using a switch statement? \n" + " 1. Characters cannot be used\n"
+ " 2. Doubles cannot be used\n" + " 3. Integers can not be used");
answer = input.next();
} while (!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if (answer.equals("1")) {
score2 = 100;
} else if (!answer.equals("1")) {
score2 = 0;
}
do {
System.out.println("c. What is the range of byte data type in Java? \n" + " 1. -128 to 127\n"
+ " 2. -32768 to 32767\n" + " 3. -2147483648 to 2147483647");
answer = input.next();
} while (!answer.equals("1") && !answer.equals("2") && !answer.equals("3"));
if (answer.equals("1")) {
score3 = 100;
} else if (!answer.equals("1")) {
score3 = 0;
}
double totalscores = score1 + score2 + score3;
results(totalscores);
}
public void results(double totalscores) {
double percentage = (totalscores) / 3;
printData(percentage);
}
public void printData(double percentage) {
System.out.println("-----------------------");
System.out.println("\tJava Certification\n" + "\t Test Results\n");
System.out.println("Name : " + name);
System.out.println("Test Registration ID:" + id);
System.out.println("Passing Score 52% ");
System.out.println("Your Score : " + percentage + "% \n");
System.out.println("Max Score --------------------100%\r\n" + "Passing Score -----------52");
}
public static void main(String[] args) {
OnlineTest onlineTest = new OnlineTest();
onlineTest.entry();
}
}
I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
return numShuffles;
}
My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5
I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".