I have written a program using method calls as opposed to nested while loops, or rather a while within a while, but for some reason the only way I can get the program to terminate is to type break in the main method after the method calls. This is not the way I was supposed to do it, any thoughts?
Also, can this be done using a for loop? As always I appreciate your advice and guidance!
Code:
import java.util.*; public class GuessNumber { public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.print("Do you want to play a game? ");//War Games! String collegeTry = read.next(); collegeTry = collegeTry.toLowerCase(); while (((collegeTry.equals("yeah")) || (collegeTry.equals("sure")) || (collegeTry.equals("ok")))) { game(); break; } } public static void game() { Scanner read = new Scanner(System.in); Random generator = new Random(); int randNum = generator.nextInt(100) + 1; // pick a number between 1 & 100 System.out.println("\nWelcome to the High-Low Guessing Game!"); System.out.println("Try to guess the number I've chosen between 1 and 100."); System.out.print("\nWhat is your guess? "); int guessNum = read.nextInt(); int count = 1; while (guessNum != randNum) { if (guessNum > randNum) { System.out.println(guessNum + " is too high."); } else { System.out.println(guessNum + " is too low."); } count++; System.out.print("What is your guess? "); guessNum = read.nextInt(); } System.out.println("\nCorrect! You only needed " + count + " guesses to get it!"); } }
Comment