JAVA CALCULATOR Exception in thread "main" java.util.InputMismatchException - java

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
at testCalculator.main(testCalculator.java:12)
I'm trying to make a working calculator, which reads even decimal numbers, but it doesn't work. At the start it was integer valid only calculator, but within 30 minutes i tried to change it. Sadly my efforts were for nothing, anybody can help me with it? How to improve this calculator, so it can take decimal numbers without errors. Thank you very much for every answer!
import java.util.Scanner;
public class testCalculator {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
while(true){
System.out.println("First Number");
double x = read.nextDouble();
read.nextLine();
System.out.println("Second Number");
double y = read.nextDouble();
read.nextLine();
System.out.println("What you want to do? + / * - ");
String z = read.nextLine();
switch(z){
case "+":
System.out.println(x + y);
break;
case "-":
System.out.println(x - y);
break;
case "*":
System.out.println(x * y);
break;
case "/":
System.out.println (x / y);
break;
default:
System.out.println("bruh");
break;
}
}
}

Given the locale info (pl_PL) the decimal separator is a comma, e.g. 21,15.
To discover such things add the line
System.out.println(java.util.Locale.getDefault());
Use the supported locales to look it up:
https://www.oracle.com/java/technologies/javase/jdk8-jre8-suported-locales.html
And get further info on the locale:
https://www.localeplanet.com/icu/pl-PL/index.html
and reference the "Decimal separator" value: ,.

Related

Command line calculator with multiple input numbers and operators?

Newbie to Java; I've created a Command line calculator that gets a double from user and gets one operation symbol and gets another double from user and the calculates the amount.
This is my code.
import java.util.Scanner;
public class forthProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double numb1, numb2, add, subtract, multiply, divide;
char operation;
while (true) {
System.out.println("Calculate: ");
numb1 = in.nextDouble();
operation = in.next().charAt(0);
numb2 = in.nextDouble();
switch (operation) {
case '+':
add = numb1 + numb2;
System.out.println(add);
break;
case '-':
subtract = numb1 - numb2;
System.out.println(subtract);
break;
case '*':
multiply = numb1 * numb2;
System.out.println(multiply);
break;
case '/':
divide = numb1 / numb2;
System.out.println(divide);
break;
}
}
}
}
What I want to figure out is how to be able to get multiple numbers from users and do multiple operations.
for example a user could type (3+4)*4/6= and get an answer.
Also I would like to implement the bedmas in the new code.
I'll appreciate your guidance.
In order to implement PEMDAS and do multiple operations, you will need to keep all input until the user sends in '='. One way to do this is reverse polish notation. Just transform the string to RPN and then run through the equation.

Invalid constant character when using switch/case?

I cannot seem to make my code work properly. I need to find the area of the square and add the units of measurement depending on what the user uses either in for inch, m for meter, cm for centimeter, and ft for feet.
public static void main (String[] args)
{
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
double side1 = sc.nextDouble();
while (side1 < 0)
{
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
side1 = sc.nextDouble();
}
char unitsMeasurement;
// prompt the user to enter the measurement unit
char units = Character.toUpperCase(status.charAt(0));
String unitsMeasurement = "";
**{
switch(units)
{
case "in":
unitsMeasurement = "inch"; break;
case "cm":
unitsMeasurement = "centimeter"; break;
case "ft":
unitsMeasurement = "feet"; break;
case "m":
unitsMeasurement = "meter"; break;
default:System.out.println("Invaild unit"); break;
}**
//Area of Square = side*side
double area = side1*side1;
**System.out.println("Area of Square is: "+area, +unitsMeasurement+);**
}
}
}
Your main problem is, that you are using a switch-case-statement on a char while all your cases are based on a String. That doesn't work together.
Some other problems are that status is never defined, therefore units can't have a value at all.
I'm not quite sure what you are trying to achieve, but I assume the following:
The user inputs the length of a square with a unit (abbreviated). The program calculates the area of the square and outputs it together with the unit (unabbreviated).
Sample input:
5cm
Sample output:
Area of square is: 25 centimeter^2
Keep in mind that an area has a squared length unit!
Based on that, here is some working code:
public static void main (String[] args) {
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
String input = sc.nextLine();
//Remove anything but digits
double side1 = Double.parseDouble(input.replaceAll("\\D+",""));
//Remove all digits
String unit = input.replaceAll("\\d","");
System.out.println(side1);
System.out.println(unit);
while (side1 < 0) {
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
input = sc.nextLine();
//Remove anything but digits
side1 = Double.parseDouble(input.replaceAll("\\D+",""));
}
switch(unit) {
case "in":
unit = "inch";
break;
case "cm":
unit = "centimeter";
break;
case "ft":
unit = "feet";
break;
case "m":
unit = "meter";
break;
default:
System.out.println("Invaild unit");
break;
}
double area = side1*side1;
System.out.println("Area of Square is: " + area + " " + unit + "^2");
}

Java validation error from user input

I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated.
If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors
Java
package calculator;
import java.util.Scanner;
public class calculator {
/**
* #param args
*/
public static void main(String[] args) {
double n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
System.out.println("Enter second number");
n2 = scannerObject. nextDouble();
Scanner op = new Scanner(System.in);
System.out.println("Enter your operation");
operation = op.next();
switch (operation) {
case "+":
System.out.println("Your answer is " + (n1 + n2));
break;
case "-":
System.out.println("Your answer is " + (n1 - n2));
break;
case "/":
System.out.println("Your answer is " + (n1 / n2));
break;
case "*":
System.out.println("Your asnwer is " + (n1 * n2));
break;
default:
System.out.println("I do not know!");}
}
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
}
and these are the error messages I get:
Errors
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at calculator.calculator.main(calculator.java:14)
I've tried so many different things but can't get it to work as I want it.
Can anyone be of any assistance here?
Thanks for reading
This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.
You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Taken from documention on Scanner
double nextDouble()
Returns the next token as a long. If the next token is not a float or
is out of range, InputMismatchException is thrown.
I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.
You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)
It seems that you are not entering any integer as input.
You can solve this by handling the exception this way :
try {
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine();
}
catch (InputMismatchException e) {
input.nextLine();
}
Your issue is at,
scannerObject. nextDouble();
You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input");
}
Then you may want to create a loop to get the input again and agin until valid input is detected.
Edit
You'll need to,
import java.util.InputMismatchException;
Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.
boolean notValidInput = true;
while(notValidInput) {
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
notValidInput = false;
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input. Please try again!");
}
}

Calculator int choice = Integer.parseInt(char_a); java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}
I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);
There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

Simple Calculator Java Coding Errors [duplicate]

This question already has answers here:
Simple Java calculator
(10 answers)
Closed 8 years ago.
Trying to make a simple calculator in Java but I keep getting errors when I try to compile it. Not sure if it's the coding or something I am doing when I compile it. Any help would be appreciated!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
Two compilation errors:
Your class name has whitespace in it: class simple calculator isn't valid, because "calculator" isn't a recognized token. Try: class SimpleCalculator. Also make it public and change the name of the file to match. (SimpleCalculator.java).
You declare variables a and b but don't give them types. Use float a = ... and double b = .... That one is a float and the other is a double is strange, but pressing on...
Other new-to-java issues to note:
You never close bucky, the scanner. This is a resource leak, and in a bigger application could be a major bug. Add bucky.close() after you read the last line from it, which is after operation = bucky.next()
the name bucky tells me absolutely nothing about what it is or what its use is. Try to use descriptive variable names. (The only main exception being single letter names for loop indices, etc).
fnum and snum are local variables that you declare but never use. Perhaps get rid of them?
Here's your code with edits made:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
I was able to compile it in the terminal with no trouble.

Categories