Repeat loop until input valid for fraction class - java

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.

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.

Trying to understanding Exit, Loop, Method and If and Else [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

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

How to print error message when user enters anything that is not a double?

I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}

Need to prompt again after entered negative value

I am trying to build a new code, and now the problem is after user entered negative value, this will print something and prompt again to enter value. What should I add after 69th line?
Here is my code:
import java.util.Scanner;
public class bchimedochir_Math
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
double userInput;
double value;
double pow;
double sqrt;
double log;
double floor;
double ceil;
double abs;
double sqrtE;
System.out.print("How many numbers would you like to process:");
userInput = input.nextDouble();
sqrtE = Math.sqrt(Math.E);
if (userInput > 0)
{
while (true)
{
System.out.println();
System.out.print("Please enter a number: ");
value = input.nextDouble();
sqrt = Math.sqrt(value);
log = Math.log(value);
ceil = Math.ceil(value);
floor = Math.floor(value);
pow = Math.pow(value, value);
abs = Math.abs(value);
System.out.println ("Using truncated integer value for exponent of power method.");
System.out.printf("Math.pow(%.4f,%.4f)=%.4f\n", ceil, ceil, pow);
if (value < 0 )
{
System.out.println ("Cannot use negative number for square root, using absolute value instead.");
System.out.printf("Math.sqrt(%4f)=%.4f\n", abs, sqrt);
}
else
{
System.out.printf("Math.sqrt(%4f)=%.4f\n", value, sqrt);
}
if (value < 0 )
{
System.out.println ("Cannot use negative number for log method, using absolute value instead.");
System.out.printf("Math.log(%.4f)=%.4f\n", abs, log);
}
else
{
System.out.printf("Math.log(%.4f)=%.4f\n", value, log);
}
System.out.printf("Math.floor(%.4f)=%.4f\n", value, floor);
System.out.printf("Math.ceil(%.4f)=%.4f\n", value, ceil);
System.out.printf("Math.abs(%.4f)=%.4f\n", value, abs);
userInput = userInput - 1;
}
System.out.printf("\n\nThe square root of e is: \nMath.e = %.4f \n", sqrtE);
}
if (userInput < 0)
{
System.out.print("You must enter a number greater than or equal to 0.\n");
}
if (userInput == 0)
{
System.out.print("No numbers to process.\n");
System.out.printf("\n\nThe square root of e is: \nMath.e = %.4f \n", sqrtE);
}
}
}
use while loop with the condition given in the if().
Also the answer for "How many numbers would you like to process:" will be a integer value, cannot be in double.
Just create a method to read positive values.
public int readPositiveInt() {
int userInput = input.nextInt();
if(userInput<0) {
System.out.println("You must enter a number greater than or equal to 0.");
return readPositiveInt();
}
return userInput;
}
I think you are trying to achieve this:
while(userInput <0){
System.out.print("You must enter a number greater than or equal to 0.\n");
userInput = input.nextInt();
}
If you want to restrict the attempts:
int MAX_ATTEMPTS = 10;
int attempts = 0;
while(userInput <0 && attempts < MAX_ATTEMPTS ){
System.out.println("You must enter a number greater than or equal to 0.\n");
userInput = input.nextInt();
attempts++;
}
if(userInput <0 ){
System.out.println("You didn't enter correct value in "+
MAX_ATTEMPTS +" attempts");
}

Categories

Resources