Reputation: 91
I'm trying to make a simple program where if the user puts in a number in the array the digit that array number equals will appear. It works perfectly unless the user puts in a number not in the array, and then puts in a number in the array. What happens is the program doesn't display the answer to the correct place.
Scanner ethan = new Scanner(System.in);
System.out.println("Enter array place: ");
int amount = ethan.nextInt();
int array[] = {2, 4, 9};
for(int i = 0; i<amount; i++)
{
if (amount == 0) {
System.out.println(array[0]);
} else if (amount == 1) {
System.out.println(array[1]);
} else if (amount == 2) {
System.out.println(array[2]);
} else {
System.out.println("Enter integer in array:");
amount = ethan.nextInt();
}
}
Upvotes: 2
Views: 56
Reputation: 15119
You should not use the number from input in the for loop
for(int i = 0; i < amount; i++){
What if I entered 0? The program would not run a single loop.
Try this, it should be valid. I've made some comments for you in the code.
int array[] = {2, 4, 9};
Scanner ethan = new Scanner(System.in);
/**
* This gets one valid number from the user
*/
public void getOneNumber() {
/**
* This is our "switch" variable
*/
boolean validIndexGiven = false;
while (!validIndexGiven)
{
/** This is actually called "array index"*/
System.out.println("Enter array index: 0 to " + (array.length - 1));
int index = ethan.nextInt();
/** Here we check if given integer is in the bounds of array.
* No need to check every possible value.
* What if we had array[100]? */
if (index >= 0 && index < array.length) {
/** Amount was a valid number. */
System.out.println(array[index]);
/** Toggling the switch */
validIndexGiven = true;
}
}
}
/**
* This prompts the user for numbers as many times as there are elements in array
*/
public void getManyNumbers() {
int length = array.length;
for (int i = 0; i < length; i++) {
getOneNumber();
}
}
Upvotes: 2
Reputation: 91
I figured it out. Here is the code (also thank you everyone who left some answers):
Scanner ethan = new Scanner(System.in);
System.out.println("Enter array place: ");
int amount = ethan.nextInt();
int array[] = { 2, 4, 9 };
while(true){
if (amount == 0) {
System.out.println(array[0]);
break;
} else if (amount == 1) {
System.out.println(array[1]);
break;
} else if (amount == 2) {
System.out.println(array[2]);
break;
} else {
System.out.println("Enter integer in array:");
amount = ethan.nextInt();
}
}
}
}
Upvotes: 0
Reputation: 1433
It seems like you want the user to be able to enter numbers as many times as there are numbers in the array (3 times, in this case). However, it seems like you only let the user enter it however many times they type in at the beginning (when it says "Enter array place: ". Why not try i<array.length
instead of i<amount
? Alternatively, you can use a while
loop, and only increment i
when the person enters a valid number.
Tip: you can say if ((amount >= 0) && (amount <= 2)) System.out.println(array[amount]);
Upvotes: 1