d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Fix My Code Plz
Add Reply New Topic New Poll
Member
Posts: 31,390
Joined: Mar 25 2009
Gold: 99.00
Mar 26 2020 03:30pm
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.
Member
Posts: 12,703
Joined: May 17 2013
Gold: 2,935.00
Mar 26 2020 04: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

This post was edited by Klexmoo on Mar 26 2020 04:09pm
Member
Posts: 31,390
Joined: Mar 25 2009
Gold: 99.00
Mar 26 2020 04:21pm
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 :)
Member
Posts: 31,390
Joined: Mar 25 2009
Gold: 99.00
Mar 26 2020 04:28pm
Like this?

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


I'm getting an error with that. Cannot cast string to int
Member
Posts: 12,703
Joined: May 17 2013
Gold: 2,935.00
Mar 27 2020 03:43am
use Integer.parseInt
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll