Why does this keep looping? - java

The error I'm getting when I try to run my program is that it keeps looping between turnFirstNumber() and turnSecondNumber() after I go through all 3 'turns' entirely the first time.
EDIT: SEE BOTTOM.
My Test Class:
public class testLock
{
public static void main (String[] args)
{
Lock testLock = new Lock();
testLock.turnLock();
return;
}
}
Here's my code segments causing me grief:
public void turnLock()
{
System.out.print("This is a lock that goes from 0 to 39. You must turn the knob clockwise first, then counterclockwise twice, ");
System.out.print("then clockwise for the final input. Specify how many revolutions you want (Positive number indicates ");
System.out.println("COUNTER CLOCKWISE. Negative number indicates CLOCKWISE.");
turnFirstNumber();
turnSecondNumber();
turnThirdNumber();
System.out.println("The combination you chose was: " + tempFirst + ", " + tempSecond + ", and " + tempThird + ".");
return;
}
private boolean turnFirstNumber()
{
revoCount = 0;
System.out.print("11111111What is your desired direction and number of revolutions? (Positive number is counterclockwise, negative number is clockwise): ");
count = in.nextInt();
if (count > 0)
isClockwise = false;
else if (count < 0)
isClockwise = true;
else
{
throw new IllegalArgumentException("Your desired direction of spinning the lock is invalid. Please choose a number other than 0.");
}
System.out.print("\n11111111111What is your desired first number?: ");
desiredNumber = in.nextInt();
if (!isClockwise) //user desires countercockwise revolution
{
do {
for (int i = 0; i < (count * 40); i++)
{
activeNumber++;
if (activeNumber > 39)
activeNumber = 0;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < count));
}
else if (isClockwise) //user desires clockwise revolution
{
do {
for (int i = 0; i < (Math.abs(count) * 40); i++)
{
activeNumber--;
if (activeNumber < 0)
activeNumber = 39;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < Math.abs(count)));
}
tempFirst = activeNumber;
if ((activeNumber == first) && (count < 0)) //if first number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
private boolean turnSecondNumber()
{
revoCount = 0;
System.out.print("2222222222What is your desired direction and number of revolutions? (Positive number is counterclockwise, negative number is clockwise): ");
count = in.nextInt();
if (count > 0)
isClockwise = false;
else if (count < 0)
isClockwise = true;
else
{
throw new IllegalArgumentException("Your desired direction of spinning the lock is invalid. Please choose a number other than 0.");
}
System.out.print("\n222222222What is your desired second number?: ");
desiredNumber = in.nextInt();
if (!isClockwise) //user desires countercockwise revolution
{
do {
for (int i = 0; i < (count * 40); i++)
{
activeNumber++;
if (activeNumber > 39)
activeNumber = 0;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < count));
}
else if (isClockwise) //user desires clockwise revolution
{
do {
for (int i = 0; i < (Math.abs(count) * 40); i++)
{
activeNumber--;
if (activeNumber < 0)
activeNumber = 39;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < Math.abs(count)));
}
tempSecond = activeNumber;
if ((activeNumber == second) && (count == 2)) //if second number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
private boolean turnThirdNumber()
{
revoCount = 0;
System.out.print("Enter '1' to twist the dial counterclockwise until you reach your desired number. Enter '-1' to twist the dial clockwise until you reach your desired number.: ");
count = in.nextInt();
if (count == 1)
isClockwise = false;
else if (count == (-1))
isClockwise = true;
else
{
throw new IllegalArgumentException("You are not supposed to do a full revolution on the third number of the combination. Now you have to restart.");
}
System.out.print("\n333333333What is your desired third and final number?: ");
activeNumber = in.nextInt();
activeNumber = Math.abs(activeNumber);
tempThird = activeNumber;
if (activeNumber > 39)
{
throw new IllegalArgumentException("You desire a number that is not on the lock. The lock goes from 0 to 39. Try again.");
}
if ((activeNumber == third) && (isClockwise)) //if third number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
EDIT: So after testing more carefully, I found that my openLock() method may be calling my turnFirst, turnSecond, and turnThird methods somehow. I commented out my turnLock() method in my test class and ran the openLock() method and it started calling turnFirst and turnSecond multiple times and finally turnThird for some reason after a few loops. Here's the openLock():
public void openLock()
{
if ((turnFirstNumber()) && (turnSecondNumber()) && (turnThirdNumber()) && (isClosed)) //if all 3 passed and lock is not open already
{
isClosed = false;
System.out.println("Your combination is correct and the lock has been opened.");
return;
}
else if (!isClosed) //lock's already open
{
System.out.println("The lock is already open.");
return;
}
else if ((!turnFirstNumber()) && (turnSecondNumber()) && (turnThirdNumber())) //first wrong
{
System.out.println("The first number you input is incorrect.");
return;
}
else if ((!turnFirstNumber()) && (!turnSecondNumber()) && (turnThirdNumber())) //first and second wrong
{
System.out.println("The first 2 numbers you input are incorrect.");
return;
}
else if ((!turnFirstNumber()) && (turnSecondNumber()) && (!turnThirdNumber())) //first and third wrong
{
System.out.println("The first and last numbers you input are incorrect.");
return;
}
else if ((turnFirstNumber()) && (turnSecondNumber()) && (!turnThirdNumber())) //third wrong
{
System.out.println("The last number you input is incorrect.");
return;
}
else if ((turnFirstNumber()) && (!turnSecondNumber()) && (!turnThirdNumber())) //second and third wrong
{
System.out.println("The second and last numbers you input are incorrect.");
return;
}
else if ((turnFirstNumber()) && (!turnSecondNumber()) && (turnThirdNumber())) //second is wrong
{
System.out.println("The second number you input is incorrect.");
return;
}
else
{
System.out.println("Your entire combination is INCORRECT. Please try again."); //all wrong
return;
}
}

Are you sure it's looping?
In your openLock method it's calling the methods turnFirstNumber, turnSecondNumber and turnThirdNumber in every if-statement.
In case the last number is incorrect, it has called the methods turnFirstNumber, turnSecondNumber and turnThirdNumber each 5 times.
I think it's better to introduce variables like firstTurnCorrect, secondTurnCorrect and thirdTurnCorrect and compare those values to get the right message:
boolean firstTurnCorrect = turnFirstNumber();
boolean secondTurnCorrect = turnSecondNumber();
boolean thirdTurnCorrect = turnThirdNumber();
if (!firstTurnCorrect && secondTurnCorrect && thirdTurnCorrect) ...
This way those methods only gets called once.

Related

Issues with counter and for loop. Assitance appreciated

Having issues with my for loops and the counter it should add up each value of the numbers I have added and ask me what that value is, at the end of the for loop. I added the number-2 to end the loop, so I tried to subtract it from the total before printing, but it doesn't work.
Help!
import java.util.*;
public class CountingCards {
public static void main(String[] args) {
Counting();
}
public static void Counting() {
Random rand = new Random();
int count = 0;
int sum = 0;
Scanner in = new Scanner(System.in);
for (int a = 0; a < 110; a++) {
int player = rand.nextInt((10) + 1);
System.out.println(" ");
System.out.println("You got this card: " + player);
System.out.println("What is the value of that card");
int answer = in.nextInt();
if (player == 1) {
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
}
if (answer != -1) {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
}
if (player == 2) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 3) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 4) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 5) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 6) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 7) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 8) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 9) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 10) {
if (answer == 1) {
count = 1;
System.out.println("That is CORRECT");
}
if (answer != 1) {
count = 1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (answer == -2) {
sum = sum - 2;
System.out.println("Your total count is: " + sum);
break;
}
sum = sum + count;
}
}
}
the sum should add all the counters I've acquired, throughout the for loop, and ask me each time to see if the answer I give them adds to the total counter each time. It's ways off and I dont know why
I could not understand what exactly this game is; but looking at your code, I guessed that you have made a logical mistake in the following line:
int player = rand.nextInt((10) + 1);
It should be
int player = rand.nextInt(10) + 1;
Second thing is, you can replace the following code:
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
}
if (answer != -1) {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
with
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
} else {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
For more help, you need to clearly mention the rules of the game.
Changing
int player = rand.nextInt((10) + 1);
to
int player = rand.nextInt(10) + 1;
should solve your problem. Hope it helps..
Have a good day !

Monty Hall lets make a deal in JAVA using simpler operators and functions

So I've been working on this assignment for about 12 hours and have been unsuccessful in covering all the parameters. I was asked to make a program based off of Monty Hall "Lets make a deal" and asked to check each user input for validity up to the switching of doors;
I'm having the following issues:
if the user wants to switch doors after a zonk is revealed they're taken back to the main menu where they're asked to pick a door. then put in a continuous input loop
if the user's input is invalid at the switch doors scenario then the same problem as above happens
problem displaying the win percentage
problem when wanting to play the game again
please help, somewhat of a beginner so criticism is more than welcomed on all parts of the code.
System.out.println("WELCOME TO 'LETS MAKE A DEAL'");
System.out.println("Please Enter 'A' to Play, 'B' To Watch, or 'Q' To Quit");
Scanner input = new Scanner (System.in);
String choice = input.next();
boolean done = false;
double wins = 0;
double loses = 0;
double games = 0;
while (!done)
{
if(choice.equals("A"))
{
System.out.println("Please Choose a door:\n");
System.out.println("[1] [2] [3]\n");
System.out.println("Type '1', '2', or '3'");
if(input.hasNextInt())
{
int chosenDoor = input.nextInt();
if(chosenDoor <= 3 && chosenDoor > 0)
{
int prizeIs = (int) ((Math.random() * 3) + 1);
int finChoice = 0;
int zonkIs = 0;
while (prizeIs == chosenDoor)
{
zonkIs = (int) ((Math.random() * 3) + 1);
while (zonkIs == prizeIs)
{
zonkIs = (int) ((Math.random() * 3) + 1);
}
}
if (prizeIs == 1 && chosenDoor == 2)
{
zonkIs = 3;
}
else if (prizeIs == 1 && chosenDoor == 3 )
{
zonkIs = 2;
}
else if (prizeIs == 2 && chosenDoor == 1 )
{
zonkIs = 3;
}
else if (prizeIs == 2 && chosenDoor == 3 )
{
zonkIs = 1;
}
else if (prizeIs == 3 && chosenDoor == 1 )
{
zonkIs = 2;
}
else if (prizeIs == 3 && chosenDoor == 2 )
{
zonkIs = 1;
}
System.out.println("\nI Will Now Reveal A Zonk\n\nDoor [" + zonkIs + "]");
System.out.println("\nKnowing This, Would You Like To Switch Doors? ('Y' or 'N') ");
String decision = input.next();
if(decision.equals("Y"))
{
System.out.println("Pick A New Door (Not The One With A Zonk)");
chosenDoor = input.nextInt();
finChoice = chosenDoor;
System.out.println("\nWell Then\n\nThe Moment You've Been Waiting For\n");
System.out.println("The Prize is in\n\nDoor [" + prizeIs + "]");
if (prizeIs == finChoice || prizeIs == chosenDoor)
{
System.out.println("\nCONGRATUALTIONS!!!\nYOU WON!!!!!");
wins++;
games++;
}
else
{
System.out.println("\n..Sorry, You Lost.");
loses++;
games++;
}
System.out.println("\nWould You Like To Play Again? ('Y' or 'N')");
decision = input.next();
if(decision.equals("N"))
{
System.out.println("\nWell Thanks For Playing\nYour Win Percentage was ");
if(wins <= 0.0 || wins < loses)
{
double percentage = 0;
System.out.printf(percentage +"%");
}
else
{
double percentage = (wins-loses)/games * 100;
System.out.printf("%5.2f", percentage +"%");
}
done = true;
input.close();
}
else if(decision.equals("Y"))
{
System.out.println("*******************************");
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else if(decision.equals("N"))
{
finChoice = chosenDoor;
System.out.println("\nWell Then\n\nThe Moment You've Been Waiting For\n");
System.out.println("The Prize is in\n\nDoor [" + prizeIs + "]");
if (prizeIs == finChoice || prizeIs == chosenDoor)
{
System.out.println("\nCONGRATUALTIONS!!!\nYOU WON!!!!!");
wins++;
games++;
}
else
{
System.out.println("\n..Sorry, You Lost.");
loses++;
games++;
}
System.out.println("\nWould You Like To Play Again? ('Y' or 'N')");
decision = input.next();
if(decision.equals("N"))
{
System.out.println("\nWell Thanks For Playing\nYour Win Percentage was ");
if(wins <= 0.0 || wins < loses)
{
double percentage = 0;
System.out.printf(percentage +"%");
}
else
{
double percentage = (wins-loses)/games * 100;
System.out.printf("%5.2f", percentage +"%");
}
done = true;
input.close();
}
else if(decision.equals("Y"))
{
System.out.println("*******************************");
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
input.next();
}
}
else if(choice.equals("B"))
{
}
else if(choice.equals("Q"))
{
done = true;
input.close();
}
else
{
System.out.println("Invalid Entry, Please Try Again..");
choice = input.next();
}
}
}
}
First, this part of the code makes no sense:
while (prizeIs == chosenDoor)
{
zonkIs = (int) ((Math.random() * 3) + 1);
while (zonkIs == prizeIs)
{
zonkIs = (int) ((Math.random() * 3) + 1);
}
}
The outer while loop here, since you change neither prizeIs nor chosenDoor inside, is going to be an endless loop.
Also, there is no point in choosing zonks out of the three doors, because after we have a prizeIs, there are only two zonks, which are the other doors. It would be best to use collections or array shuffles, I suppose, but if you are not allowed, you could list the possibilities.
if ( prizeIs == chosenDoor ) { // Note it's an if, not a while.
boolean chooseFirstZonk = Math.random() < 0.5; // 50% chance
switch ( prizeIs ) {
case 1:
if ( chooseFirstZonk ) {
zonkIs = 2;
} else {
zonkIs = 3;
}
break;
case 2:
if ( chooseFirstZonk ) {
zonkIs = 1;
} else {
zonkIs = 3;
}
break;
case 3:
if ( chooseFirstZonk ) {
zonkIs = 1;
} else {
zonkIs = 2;
}
break;
}
}
Then this if:
if (prizeIs == 1 && chosenDoor == 2)
becomes an else if to the above if.
Next, you have a bit of a misunderstanding about the game. Now that the zonk has been revealed, there are only two doors that are covered. If the user chooses to switch, he is not supposed to select a new door out of three. One is known to be a zonk, and one is known to be his previous choice which he chose to abandon. So when a user wants to switch, you are supposed to simply change chosenDoor to the unrevealed door.
If the original chosen door is the prize door, you are supposed to switch chosenDoor to the second zonk. So if prizeIs is 1, and so is chosenDoor, and zonkIs is 2, you change chosenDoor = 3. If zonkIs is 3, you do chosenDoor = 2.
If the original chosen door is not the prize door, you are supposed to assign chosenDoor = prizeIs - as the user chose a zonk, and you revealed the other zonk, so the only one remaining is the prize door.
So no user input is required in this case.
So you will need to change that large if-else. If the user chose to switch, you do the calculation. This if has no else, as when the user didn't say yes, he means to keep his original choice. At this point, check if chosenDoor == prizeIs, and calculate the percentages.
Calculations
First, you only need to keep two variables. Like wins and losses, or wins and games, or losses and games. You can always calculate losses as games - wins.
So always do games++, don't do losses at all, and do wins++ when the player wins.
Now calculating the success percentage does not require those ifs. wins cannot be less than zero. it also can't be greatar than games.
But what is important is to remember that if you divide an integer by an integer, you are going to get integer division. That is, 5/10 gives you zero, not 0.5, because it's not an integer.
So it's important to convert one of the numbers to double before you divide. One simple way to do this is to change the 100 to 100.0, and move it to the beginning:
double percentage = 100.0 * wins / games;
This way, 100.0 * wins automatically converts the value of wins to double. Therefore, when the result of it is divided by games, the value of games is also converted to double, and there is no integer division.

How to go back into a while-loop, from an if statement?

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

While loop output

The program will generate the correct output for the first number guess but after the user inputs the second guess, there is no output at all. Please help! THANKS
final int number = (int)((Math.random()*99)+1);
int counter = 0;
System.out.print("Enter a guess between 1 and 100: ");
while (keyboard.nextInt() > number) {
System.out.println("Your guess was too high. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() < number) {
System.out.println("Your guess was too low. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() == number) {
System.out.println("Congratulations! Your guess was correct!");
counter++;
System.out.println("I had chosen " + number + " as the target number.");
System.out.println("You guessed it in " + counter + " tries.");
if (counter == 1) {
System.out.println("That was lucky!");
}
if (counter >= 2 || counter <= 4) {
System.out.println("That was amazing!");
}
if (counter == 5 || counter == 6) {
System.out.println("That was good.");
}
if (counter == 7) {
System.out.println("That was OK.");
}
if (counter == 8 || counter == 9) {
System.out.println("That was not very good.");
}
if (counter >= 10) {
System.out.println("This just isn't your game.");
}
you really need to change your design pattern.
Once you fail to satisfy the conditions in 1 of those while loops, you code will never go back.
you should only have 1 while loop for the guessing phase. you code should look like this
while(someCondition)
{
int num = keyboard.nextInt()
if (num > number) {
...
}
else if (num < number) {
...
}
else if (num == number) {
...
}
}
Your while loops should be if statements.
There should be a while loop around (practically) all your code
You code should roughly look like:
while(true) {
// prompt for input
// read input
// break from loop if input is the exit input, eg -1
// check input - essentially change your whiles to ifs
}
This block doesn't seem to work as intended:
while (keyboard.nextInt() > number) {
System.out.println("Your guess was too high. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() < number) {
System.out.println("Your guess was too low. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
Assume the user enters -1 and then 101. You'll end up in the next loop. Thus you might want to change it to something like this:
boolean retry = true;
while ( retry ) {
counter++;
int n = keyboard.nextInt();
if( n > number ) {
System.out.println("Your guess was too high. Try again.");
}
else if( n < number ) {
System.out.println("Your guess was too low. Try again.");
}
else {
//number found
retry = false;
}
if( retry ) {
System.out.prnt("Enter a guess between 1 and 100: ");
}
}
There is some problem in how you use the while statement.
Here you can find the correct version of your code:
public static void main(final String[] args) {
final Scanner keyboard = new Scanner(System.in);
final int number = (int) ((Math.random() * 99) + 1);
int counter = 0;
System.out.print("Enter a guess between 1 and 100: ");
int user_number;
do {
user_number = keyboard.nextInt();
if (user_number > number) {
System.out.println("Your guess was too high. Try again.");
System.out.print("Enter a guess between 1 and 100: ");
counter++;
} else if (user_number < number) {
System.out.println("Your guess was too low. Try again.");
System.out.print("Enter a guess between 1 and 100: ");
counter++;
}
} while (user_number != number);
System.out.println("Congratulations! Your guess was correct!");
counter++;
System.out.println("I had chosen " + number + " as the target number.");
System.out.println("You guessed it in " + counter + " tries.");
if (counter == 1) {
System.out.println("That was lucky!");
}
if ((counter >= 2) || (counter <= 4)) {
System.out.println("That was amazing!");
}
if ((counter == 5) || (counter == 6)) {
System.out.println("That was good.");
}
if (counter == 7) {
System.out.println("That was OK.");
}
if ((counter == 8) || (counter == 9)) {
System.out.println("That was not very good.");
}
if (counter >= 10) {
System.out.println("This just isn't your game.");
}
}
while(someCondition)
{
if (keyboard.nextInt() > number) {
...
} else if(keyboard.nextInt() < number) {
...
} else {
...
}
}

Checking for user input to be only integers in Java

I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}

Categories