d2jsp
d2jsp Forums > Programmer's Haven > Java, Visual Basic, VBScript > Fix My Code Plz
Add Reply New Topic New Poll
ferf
#1 Mar 26 2020 03:30pm
Group: Member
Posts: 30,325
Joined: Mar 25 2009
Gold: 0.00
Code
package com.company;

import java.util.Random;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
Random random = new Random();

boolean condition1 = true;
boolean condition2 = true;




while (condition1) {
int intRandom = random.nextInt(10);
System.out.println("Enter 1 to play, or 2 to quit!!");
int option = scan.nextInt();
switch (option) {
case 1:
while (condition2) {
System.out.println("Guess which number has been chosen from 0-9: ");
int guess = scan.nextInt();
if (guess == intRandom) {
System.out.println("Your guess was correct!! Number was " + intRandom);
break;
} else {
System.out.println("You chose wrong, keep guessing!!");
}

}

case 2:
condition1 = false;
break;

}


}

}
}











So with:

case 2:
condition1 = false;



^it does exit the program when you press 2 as it should BUT with condition1 = false, it doesn't relooop the programing after you guess the correct number it just exits program




and without condition 1 = false in case 2
it does reloop the program prompting user to play again or exit program, But pressing 2 doesn't work exiting program










Been stumped on this for hours, kinda stumped, plz help. Thanks guys. Hopefully all this makes sense.
Klexmoo
#2 Mar 26 2020 04:05pm
Group: Member
Posts: 9,976
Joined: May 17 2013
Gold: 73,546.00
you need to break after the while loop in case 1

you also have an issue with the input when the number is 0. If you type 0, scan.nextInt wont read it properly. Use scan.next() and cast that to an int instead

This post was edited by Klexmoo on Mar 26 2020 04:09pm
ferf
#3 Mar 26 2020 04:21pm
Group: Member
Posts: 30,325
Joined: Mar 25 2009
Gold: 0.00
Quote (Klexmoo @ Mar 26 2020 05:05pm)
you need to break after the while loop in case 1

you also have an issue with the input when the number is 0. If you type 0, scan.nextInt wont read it properly. Use scan.next() and cast that to an int instead


Ah man, thanks so much works now :)
ferf
#4 Mar 26 2020 04:28pm
Group: Member
Posts: 30,325
Joined: Mar 25 2009
Gold: 0.00
Like this?

int guess = (int) scan.next();


I'm getting an error with that. Cannot cast string to int
Klexmoo
#5 Mar 27 2020 03:43am
Group: Member
Posts: 9,976
Joined: May 17 2013
Gold: 73,546.00
use Integer.parseInt
Go Back To Java, Visual Basic, VBScript Topic List
Add Reply New Topic New Poll