Trying to understanding Exit, Loop, Method and If and Else [JAVA] - java

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

Related

How to make this calculator to only accept numbers in first two input's and loop till they are correct

Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.

Java Scanner nextInt problem, need to stop error when entering a string and loop back

private static int getNumberOfPlayers() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
// controlling input, at least 2 - at most 4 players can play the game
while (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " players");
}
return numOfPlayers;
}
When the player enters anything other than and int here the game crashes. I would like a sout message to tell the user and loop back so they can try again instead of crashing. Could someone please help me modify this method to implement this functionality. Any help would be greatly appreciated.
Simply use exception handeling like this. This might be what you want:
private static int getNumber() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
int newNumOfPlayers;
// controlling input, at least 2 - at most 4 players can play the game
while(true){
if (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
try{
newNumOfPlayers = sc.nextInt();
}catch(Exception ex){
System.out.println("Please select a number only");
sc.next();
continue;
}
numOfPlayers = newNumOfPlayers;
System.out.println("You have selected " + numOfPlayers + " players");
return numOfPlayers;
}
}
}

Repeat loop until input valid for fraction class

I am doing a simple fraction test class. I want my program to do this.
IF a user input 0 > the loop repeats until the user enter a number that not 0
In my class, it not doing that. I tried to mixed it with do while conditions with if statements plus initializing if the statement true or false. Im stuck so please I need help.
Here my fraction Class:
import java.util.*;
public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
} while (den != 0 && !valid);
System.out.println("Decimal is " + result(num, den));
}
public static double result(int x, int y) {
return (x / y);
}
}
Here the program once I run the Test
The question is not completely clear but I think that you are asking that whenever denominator becomes zero continue loop else calculate answer and return value. I made some changes to your code according to that
public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
while(den == 0) {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
}
System.out.println("Decimal is " + result(num, den));
return;
}
public static double result(int x, int y) {
return ((1.0)*x / y);
}
}
change the code in the main-method to this:
Scanner input = new Scanner(System.in);
int num, den;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den!=0)
System.out.println("Decimal is " + result(num, den));
else
System.out.println("Denominator shouldnt be 0");
} while (den == 0);
input.close();
There was no need to initialized 'den' as the value is anyways replaced.
There was no need of having 'boolean variable' as its value never change
if den==0, no need to re-ask for inputs within the loop as the loop should
anyways re-run
I would just separate your input validations:
System.out.println("Please enter the numerator: ");
num = input.nextInt();
do{
System.out.println("Please enter the denominator: ");
System.out.println("denominator cannot be zero");
den = input.nextInt();
} while (den == 0);
System.out.println("Decimal is " + result(num, den));
If you need an input validation for your numerator just do a do while around that. Also your boolean value for valid is always true. Never modified to be false. Logic (x ^ True) will always be if x is true.

Scanner object does not return intended result

I am trying to use the scanner object to validate some user input. According to my requirement if user input is 100>inputs<0 I need to provide some console output. However, the following code does not work when I enter 100/0 and provides me some empty console output. I tried to test this code block with 102 and -1 with same (empty) console output
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
}else if (sc.nextInt() > 100){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else if (sc.nextInt() < 0){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else {
score = sc.nextInt();
break;
}
}
return score;
}
The error is causing because of using nextInt() in the if else block . Use the method hasNextInt() and store the value in a temporary variable before validating the value .
You should not read from the Scanner several times. Just read the number once via nextInt into the variable and check it. Otherwise on every if branch you will be prompted for a new number.
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}

Having trouble with loop in java

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();
}
}

Categories

Resources