Try and catch causing an error with my public void - java

Before you ask, I have already looked at other questions, they just seem to be for slightly different things.
I'm new to java and currently learning, so I made this narcissistic program that I'm going to make into a multi-tool sort of thing. That part doesn't really matter.
Basically, I'm making a text input calculator, where you type in numbers and operations and stuff, but it's fairly simple. However, in the input area, I'm trying and catching in case the user types something that isn't a number. But, this makes the variables of x and y (user inputs) to be uninitialized and not readable when initializing the separate public void calculator(variables). This is my code (I've only included the calculator part, the rest is unrelated and all working fine, also I know x is differently handled to y, I was testing them both)
public void calculatorvariables() {
System.out.println("Please enter the first number in your calculation.");
double x = scanner.nextDouble();
if(x != (double) x) {
System.out.println("An error occurred! Did you input nothing or something other than a number? Returning to variable input screen!");
} else
System.out.println("Please enter the operator. Valid operators are: '+', '-', '*', '/'");
String operation = scanner.next();
System.out.println("Please enter the second number in your calculation.");
try {
double y = scanner.nextDouble();
} catch (NumberFormatException e) {
System.out.println("An error occurred! Error message: " + e.getMessage() + " Did you input nothing or something other than a number? Returning to variable input screen!");
}
new FirstClass().calculator(x, operation, y);
}
public void calculator(double x, String operation, double y) {
if(operation.equals("+")) {
System.out.println(x + y);
}
else if(operation.equals("-")) {
System.out.println(x - y);
}
else if(operation.equals("*")) {
System.out.println(x * y);
}
else if(operation.equals("/")) {
System.out.println(x / y);
}
else {
System.out.println("Unknown operation! Returning to input area!");
new FirstClass().calculatorvariables();
}
System.out.println("Do you want to do another calculation? Y/N");
doAnotherCalculation = scanner.next().equalsIgnoreCase("Y");
if (doAnotherCalculation == true) {
new FirstClass().calculatorvariables();
}
else {
new FirstClass().mainmenu();
}
}
Any help would be appreciated!

You should declare the variable outside of the try/catch bit, like this:
double y;
try {
y = scanner.nextDouble();
catch (Exception e) {
// Exception handling
}

This should work
import java.util.Scanner;
public class TestSo{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
new TestSo().calculatorvariables();
}
public void calculatorvariables() {
System.out.println("Please enter the first number in your calculation.");
double x = scanner.nextDouble();
if(x != (double) x) {
System.out.println("An error occurred! Did you input nothing or something other than a number? Returning to variable input screen!");
} else
System.out.println("Please enter the operator. Valid operators are: '+', '-', '*', '/'");
String operation = scanner.next();
System.out.println("Please enter the second number in your calculation.");
double y = scanner.nextDouble();
calculator(x, operation, y);
}
}
public void calculator(double x, String operation, double y) {
if(operation.equals("+")) {
System.out.println(x + y);
} else if(operation.equals("-")) {
System.out.println(x - y);
} else if(operation.equals("*")) {
System.out.println(x * y);
} else if(operation.equals("/")) {
System.out.println(x / y);
} else {
System.out.println("Unknown operation! Returning to input area!");
calculatorvariables();
}
System.out.println("Do you want to do another calculation? Y/N");
boolean doAnotherCalculation = scanner.next().equalsIgnoreCase("Y");
if (doAnotherCalculation == true) {
calculatorvariables();
} else {
System.out.println("Done! Exiting");
}
}
}

Related

How to loop the following code?

I'm really new to java and I cannot find a way around this. I want to make a program that tells you that a number is either positive or negative, regardless if it is int or double. But after the program is executed, I want it to loop and ask again for input from the user, to execute the code again and again and again, as long as there is user input. Can I do that in java?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
}
}
Here is a one of the approach which is good start for you to understand what wonders pattern matching can do in Java and it can be improved by testing it against exhaustive data points.
This also shows how to use while-loop, overloading methods and ternary operator instead of nested if-then-else.
As you are learning, you should also use debugging feature of editors and also use system.out.println to understand what code is doing.
I am ending the program when user presses just enter (empty string).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = "Input your number: ";
System.out.print(userInput);
String input = scanner.nextLine();
// look for integer (+ve, -ve or 0)
if (input.matches("^-?[0-9]+$")) {
int z = Integer.parseInt(input);
System.out.println(display(z));
// look for double (+ve, -ve or 0)
} else if (input.matches("^-?([0-9]+\\.[0-9]+|[0-9]+)$")) {
double z = Double.parseDouble(input);
System.out.println(display(z));
// look for end of program by user
} else if (input.equals("")) {
System.out.println("Good Bye!!");
break;
// look for bad input
} else {
System.out.println("Hey! Only numbers!");
}
}
scanner.close();
}
// handle integer and display message appropriately
private static String display(int d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
// handle double and display message appropriately
private static String display(double d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
}
Sample Run:
Input your number: 0
0 is equal to 0
Input your number: 0.0
0.0 is equal to 0
Input your number: -0
0 is equal to 0
Input your number: -0.0
-0.0 is equal to 0
Input your number: 12
12 is positive
Input your number: -12
-12 is negative
Input your number: 12.0
12.0 is positive
Input your number: -12.0
-12.0 is negative
Input your number: 12-12
Hey! Only numbers!
Input your number: ---12
Hey! Only numbers!
Input your number:
Use this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Console console = new Console();
while(true) {
// Take your input
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
// Ask for exit
System.out.print("Want to quit? Y/N")
String input = console.readLine();
if("Y".equals(input))
{
break;
}
}
}
}

Looping for odd and even number in java

how do i repeatedly ask the user to enter an input until the user enters a negative number. If the user enters a negative number or 0, the program will end?
import java.util.Scanner;
public class OddEvenInt {
public static void main(String args[]) {
Scanner s = new Scanner(System. in );
int x;
do {
System.out.println("Enter an integer to check if it is odd or even ");
x = s.nextInt();
if (x % 2 == 0)
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
} while (x % 2 == 0);
}
}
You gotta change the while clause :
while (x>0)
use < and >
public static void main(String[] arguments) {
Scanner s = new Scanner(System.in);
int x = 0;
do {
System.out.println("Enter an integer to check if it is odd or even ");
try {
x = Integer.parseInt(s.nextLine());
if (x > 0) {
System.out.println("You entered an even number.");
} else if (x == 0) {
System.out.println("You entered 0, thats not negativ or positiv.");
} else {
System.out.println("You entered an odd number.");
}
} catch (Exception e) {
//e.printStackTrace();
System.out.println("U call this an Integer? :P");
}
} while (x > 0);
return;
}
last edit: check if your input is numberic, if you want to check the error you can remove // from the catch-block

Java Character Input With Loop?

Guys I want to write a program which find Nominator and Denominator with Exception Handling and calculate their result. I also added a Simple Interface which is Would you like to continue press 'y'. or 'n'. Character is in Lower Case.
I Want that Interface Occur only on two things.When Program Catch the Wrong Input. And When Result Is Calculated.
Problem is when user press 'n' it does not quit.Or When user enter any characters like 'aadswe' Interface does not again appear. I'm Stuck at this Problem.
public class Main {
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
}
while (m == 'y');
}
}
Use following code-
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
while(m!='y'&& m!='n'){
System.out.println("you can press only 'y'or'n' "+ m+ " is not allowed!!") ;
m = s.next().charAt(0);
}
}
while (m == 'y');
System.out.println("Has been quit");
}

re-prompt user after invalid input in java (try and catch )

Right now, it loops infinitely on the catch after one error. How can I make it go back to the try after a catch? boolean condition is declared properly, no compilation errors or anything. The rest of the code in the class is kind of a mess as I'm waiting for an answer about the re-trying.
double base = 0;
double height = 0;
double area = 0;
boolean again = true;
while (again) {
try {
System.out.print("Enter the length of base of triangle in cm : ");
base = input.nextDouble();
again = false;
} catch (Exception ex) {
System.out.println("Invalid input");
input.next();
}
try {
System.out.print("Enter the length of height of triangle in cm : ");
height = input.nextDouble();
} catch (Exception ex) {
System.out.println("Invalid Input");
String next = input.next();
}
area = (base * height) / 2;
use hasNextDouble() instead of using try/catch exception since you are not explicitly catching InputMismatchException
while (again) {
// if the next is a double, print the value
if (input.hasNextDouble()) {
base = input.nextDouble();
System.out.println("You entered base: " + base);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}
}
again = true;
while (again) {
// if the next is a double, print the value
if (input.hasNextDouble()) {
height = input.nextDouble();
System.out.println("You entered height: " + height);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}
}
area = (base * height) / 2;

simple Java calculator - while loop until answer is 0 [duplicate]

This question already has answers here:
Basic Java: While loop for basic quiz?
(5 answers)
Closed 8 years ago.
Really new to java and having some trouble with this assignment. The assignment was to:
Write a simple calculator program that prints a welcome
message, accepts a simple arithmetic expression from the user, and
performs the requested operation. Your program should repeat this
until both operands are 0 and then exit.
It's running fine but I'm not sure how to get a handle on the While Loop so that the calculator will continue until the answer is 0. Sorry if this is a really basic question. Any help would be appreciated.
import java.util.Scanner;
class Calculator{
public static void main(String[] args)
{
System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!");
System.out.println("Enter an integer operation: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
String operation= input.next();
int y = input.nextInt();
while(x + y != 0){
if(operation.equals("+")){
System.out.println(x + y);
}
else if(operation.equals("-")){
System.out.println(x - y);
}
else if(operation.equals("*")){
System.out.println(x * y);
}
else if(operation.equals("/")){
System.out.println(x / y);
}
else if(operation.equals("%")){
System.out.println(x % y + y);
}
else {
System.out.println("Operation is invalid.");
}
System.out.println("Enter an integer operation: ");
if(x + y != 0);
break;
}
}
}
use switch case in place of if else statement
if(a !=0 && b!=0)
{
switch(ch)//ch is where you stored the operator
{
case '-': System.out.println(a - b);
break;
case ' +':System.out.println(a+b);break;
}
else
{
System.out.println("Enter an integer operation: ");}
To solve the problem you mentioned above.
Write a simple calculator program that prints a welcome message, accepts a simple arithmetic expression from the user, and performs the requested operation. Your program should repeat this until both operands are 0 and then exit.
you should pay much attention to the following tips:
"until both operands are 0", so you can just loop out on the condition "x+y != 0", for example, x=5,y=-5,you can't just loop out.
"repeat" means you should assign new int value to the x and y variable in the while loop.
here's the code, may help you
import java.util.Scanner;
class Calculator{
public static void main(String[] args){
System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!");
System.out.println("Enter an integer operation: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
String operation= input.next();
int y = input.nextInt();
while(x != 0 && y != 0){
if(operation.equals("+")){
System.out.println(x + y);
}
else if(operation.equals("-")){
System.out.println(x - y);
}
else if(operation.equals("*")){
System.out.println(x * y);
}
else if(operation.equals("/")){
System.out.println(x / y);
}
else if(operation.equals("%")){
System.out.println(x % y + y);
}
else {
System.out.println("Operation is invalid.");
}
System.out.println("Enter an integer operation: ");
x = input.nextInt();
y = input.nextInt();
}
}
}

Categories

Resources