I am trying to get my code to loop back to the beginning of the program after the user completes one of the options. I cannot seem to figure out how to get it to work properly. Here is my code so far
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
boolean opt1Done = false;
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
num1 = console.nextInt();
num2 = console.nextInt();
num3 = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
System.out.println("Enter a value for num2 between 1 and 100.");
System.out.println("Enter a value for num3 between 1 and 100.");
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
//...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i=0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
//... do whatever to determine if triangle or not
if (num1+num2>num3 && num1+num3>num2 && num2+num3>num1)
{
System.out.print("TRIANGLE");
}
else
{
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
}
}
}
Basically I need it so that after the user enters 2 and completes option 2, the program will then go back to the beginning and ask again to choose which option the user wants. How can I get this to work properly? Also if anything else is wrong with the code that I do not see please let me know. Thanks
What you need is put this whole bunch of code in while loop which will always be true and ask the user input again at end. If user presses 4 which i think is exit just exit the program by using break in your while loop.
int input;
do {
//---
//The rest of your logic
//---
} while(input != 4);
You can try something like this.
Boolean p = true;
while(p){
System.out.println(
" Select an option:\n" +
"1: Enter three numbers between 1 and 100.\n" +
"2: Order your number in ascending order\n"+
"3: Determine if the three inputs form a triangle\n"+
"4: Exit\n"
);
switch(){
case 1:
.
.
.
case 4:
System.exit();
}
}
Related
Hello guys I need help with my code. I am trying to understand how to use the method, loop,if-else statement, and exit code. So I'm writing a simple calculation base on the user choice but right now I can't figure out how to make the input read to loop back when user input else than the number (mean no alphabet are allowed) and it will continue back to the option till the user enter the right option that is either 1 or 2.
Do let me know if I make any mistake or is there a way to simplify this code more.
WANT OUTPUT TO BE LIKE THIS:-
[1] Calculation
[2] Exit
Your choice: a
Please choose only 1 or 2
[1] Calculation
[2] Exit
Your choice: 1
Enter 1st number: 1
Enter 2nd number: 1
Total: 2
CODE:-
import java.util.Scanner;
public class Testing {
int ans;
boolean Loop = true;
public void SimpleCalculation() {
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
System.exit (0);
}
public static void main(String[] args) {
Testing t = new Testing();
t.SimpleCalculation();
}
}
I have updated your code :
public class Testing {
public static void SimpleCalculation() {
boolean Loop = true;
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
while(!input.hasNextInt()) {
System.out.println("Please choose only 1 or 2");
input.nextLine();
continue;
}
int ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
}
public static void main(String[] args) {
SimpleCalculation();
}
}
Output :
[1] Calculation
[2] Exit
Your choice: a
Please choose only 1 or 2
[1] Calculation
[2] Exit
Your choice: 1
Enter 1st number: 1
Enter 2nd number: 2
Total: 3
Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}
Hello there fellow coders. Just a noob here that is currently stuck in a pickle.
I am coding a math training program, and am needing to loop back to my main menu.
There is an infinite loop i am having trouble getting out of. If the user keeps answering the correct answer, it just keeps on asking for another problem. Selecting yes will generate a new answer and will keep doing so (infinite). Selecting no will terminate the program.
How do i make is so if they select no, it takes the user back to the main menu?
Also, how to make it so if they select yes, the problem only loops a new equation at max 10 times before taking the user back to my main menu.
This is my Code:
import java.util.Scanner;
import java.util.Random;
public class MathPracticeProgram
{
public static void main(String[] args)
{
//Scenario: Make a practice program for Addition, Subtraction, Multiplication, and Division. Include exit option as well.
Random rand = new Random ();
Scanner scan = new Scanner (System.in);
int menu = (5);
int num1, num2, user_answer, total;
System.out.println("Math Practice Porgram");
System.out.println("Please Input Your Choice via the number\n");
System.out.println("1. Addition\n2. Subtraction\n 3. Multiplication\n 4. Division\n Exit Program by entering 0");
System.out.println("\nYour choice:");
menu = scan.nextInt();
System.out.println("\n");
//Menu Selection
if (menu <= 5 || menu > 0)
{
switch(menu)
{
//Exit
case 0:
{
System.out.println("Thank you for using my math practice program.");
}
break;
//Addition
case 1:
{
System.out.println("You have selected Addition");
String user_again;
do
{
num1 = rand.nextInt(99);
num2 = rand.nextInt(99);
int counter = 0;
do
{
System.out.println("New solution to solve: ");
System.out.println(num1 + " + " + num2 + " = ");
user_answer = scan.nextInt();
System.out.println("\n");
total = num1 + num2;
if(user_answer != total)
{
System.out.println("Incorrect...");
counter++;
}
}while (user_answer != total && counter < 3);
System.out.println("Correct! Do you want another problem? yes or no: ");
user_again = scan.next();
}while(user_again.equalsIgnoreCase("yes"));
System.out.println("\nChanging to Main Menu\n");
}
break;
//Subtraction
case 2:
{
}
break;
//Multiplication
case 3:
{
System.out.println("Multiplication");
}
break;
//Division
case 4:
{
System.out.println("Division");
}
break;
}
}
}
}
I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.
The program I am trying to finish needs to read in three numbers from the user and then store them in the variables num1, num2 and num3 so that they can be used in steps 2 and 3. The problem I am having is that when the program loops through after the user inputs their numbers and tries to move on to step 2 or 3, it says must complete step 1 first.
This is my code as of right now:
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
int input;
do {
boolean opt1Done = false;
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
num1 = console.nextInt();
num2 = console.nextInt();
num3 = console.nextInt();
input = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
System.out.println("Enter a value for num2 between 1 and 100.");
System.out.println("Enter a value for num3 between 1 and 100.");
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
//...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
//... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2 && num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
if (answer == 4) {
System.exit(0);
}
}
} while (input != 4);
}
}
Do I need to add another loop or change the one already have?
Move the boolean declaration opt1Done and the numbers outside the loop and read input after every user prompt.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class ReadChar {
public ReadChar() {
// TODO Auto-generated constructor stub
}
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 0;
int num2 = 0;
int num3 = 0;
boolean opt1Done = false;
while (true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out
.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
// do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
// ...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out
.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
// ... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2
&& num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out
.println("you must complete Step 1 before Step 3");
}
}
if (answer == 4) {
System.exit(0);
}
}
}
}
You don't loop over the instructions. Every time you have a step completed, the program then ends and the next time you run it, nothing you've done before is saved.
You need an outer loop to iterate over commands:
public static void main(String[] args) {
int num1;
int num2;
int num3;
boolean opt1Done = false;
while (true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
//rest of your code here
}
}
It seems that you must loop until the user choose the option 4. I don't see any loops that encompass the options asking questions.
Hope this helps
Introduced a while loop and opt1True should outside of the loop
check for is answer 4 is inside answer 3. So moved that in else if to be same level with other answer checks
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 0;
int num2 = 0;
int num3 = 0;
boolean opt1Done = false;
while(true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
// do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
// ...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
// ... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2
&& num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
} else if (answer == 4) {
System.exit(0);
}
}
}
you are putting condition in wrong place.
as i am thinking first check answer from user then take those 3 numbers inside first condition as
int answer = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
}
and move this line outside of loop
boolean opt1Done = false;
All you had to do was add a while loop to your logic and reorder it.
boolean opt1Done = false;
int num1, num2, num3;
while(answer != 4){
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
}
...
if (answer == 4) {
System.exit(0);
}
}
}
}
Your problem was every time you were looping you were re-declaring and setting the boolean variable to false. Plus your console.nextInts() were in the wrong spot. Also do while is not necessary in this case because the starting value of answer is null and therefore is not equal to four.