I keep getting "Exception in thread "main" java.util.InputMismatchException"? - java

I made a Java calculator, but when I enter a number that's really long, I get this error:
Exception in thread "main" java.util.InputMismatchException: For input string: "77777777777777777777777"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at question1.Question1.main(Question1.java:26)
Here's my coding:
package question1;
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {int n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Please enter first number.");
n1 = scannerObject.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter your operation.");
operation = op.next();
System.out.println("Please enter second number.");
n2 = scannerObject.nextInt();
switch (operation) {
case "+":
System.out.println("Your result is " + (n1 + n2));
break;
case "-":
System.out.println("Your result is " + (n1 - n2));
break;
case "/":
System.out.println("Your result is " + (n1 / n2));
break;
case "*":
System.out.println("Your result is " + (n1 * n2));
break;
default:
System.out.println("Could not compute. Please only enter integers.");
}
}
}
Thanks. :)

The number 77777777777777777777777 (23 digits) is too long to fit in an int, because the maximum int possible is about 2 billion (10 digits). It's also too long to fit in a long, whose maximum value is 19 digits.
Either include an error message stating that the number is too big, or switch your datatype to BigInteger, by using Scanner's nextBigInteger method.

Related

How can I restrict the input char value?

I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.
package calculator;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
char operator;
Double num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.println("Enter the operator: +,-,*,/,% ");
operator = input.next().charAt(0);
//user input
System.out.println("Enter the First Number:");
num1 = input.nextDouble();
System.out.println("Enter the Second Number:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1+num2;
System.out.println(num1+" + "+num1+" = " + result);
break;
case '-':
result = num1-num2;
System.out.println(num1+" - "+num1+" = " + result);
break;
case '*':
result = num1*num2;
System.out.println(num1+" * "+num1+" = " + result);
break;
case '/':
result = num1/num2;
System.out.println(num1+" / "+num1+" = " + result);
break;
case '%':
result = num1%num2;
System.out.println(num1+" % "+num1+" = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
console output
Enter the operator: +,-,*,/,%
7
Enter the First Number:
5
Enter the Second Number:
5
Invalid operator
if(Character.isDigit(c)){
// what you want for true
}
else{
// what you want for false
}
This may help you.
Java or any other programming languages run code sequentially.
Here once the operator is entered you can check to proceed further for other statements.
The logic of code how you write, that way it is executed.
So in this case, once you take value for operator check whether that operator is allowed in your case or not.
If allowed then run the further code else not run that.

Java - How do I ask input from user to continue or stop at his/her wish? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner, and I would like to know on how do I get this program out of bugs-
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.next().charAt(0);
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
System.out.println("Continue? Type Y to continue or N to end: ");
String st = sc.nextLine();
if(st.equals("n")) {
stop = true;
}
else {
stop = false;
}
} while(!stop);
}
}
There are no errors at all, these are my wrong-doings in the program. After all the calculations are done, it puts me through a loop, and I don't seem to quite figure it out, on how to get the user input. It comes back to the start.
This is all I can put up, since I really don't have much to tell, if anything, I will edit this questions as users ask questions.
Thanks:)
Replace String st = sc.nextLine() by String st = sc.next().
At this point the scanner has a line break in its buffer (remaining from reading the operator).
nextLine() returns whatever is left in the buffer, it does not wait for additional user input.
By calling next() instead you tell the scanner that you want to read another token. The line break is less than a token, so Scanner waits for additional user input.
You should put a nextLine(); after every nextFoo(); to consume the new line character
Also change to sc.nextLine().charAt(0); as suggested in the comments
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.nextLine().charAt(0);//change
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
// better check
String st ="";
do {
System.out.println("Continue? Type Y to continue or N to end: ");
st = sc.nextLine();
}while (!st.equals("N") || !st.equals("Y"));
if(st.equals("N")) {
stop = true;
}
else if (st.equals("Y")) {
stop = false;
}
} while(!stop);
}
}
Note that you didn't do a very good check to see if user wants to continue
I just suggest using something like this
More info about your problem

Cannot be resolved error in java, any fixes? [duplicate]

This question already has answers here:
Java: Unresolved compilation problem
(10 answers)
Closed 3 years ago.
This is the error I am getting and I cant seem to figure out how to fix it.
I was trying to make it so that once you have finished your calculations, the program asks you if you want to perform them again.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
retry cannot be resolved
yes cannot be resolved to a variable
My code(don't judge, this is my first program in java):
package calculatorpls;
import java.util.Scanner;
public class calc {
public static void main(String[]Args)
{
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
String retry = num.nextLine();
String again = "yes";
}while(retry.equalsIgnoreCase(again));
}
}
I fixed it for you.
String retry;
String again;
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
retry = num.next();
again = "yes";
}while(retry.equalsIgnoreCase(again));
I'm answering just to expand on nusaK's answer.
You should declare utilities like Scanner which may be used multiple times outside of for loops.
When you put the Scanner num = new Scanner(System.in); inside a loop, a new Scanner Object will be created every time the loop runs. Since we're always scanning from System.in, we can use the same object to scan for all iterations.
Since Java manages memory by itself, it isn't much of a problem but it might be in other languages.
Scanner num = new Scanner(System.in);
String again = "yes"; // you can initialize again here
String retry=""; // always initialize in languages like Java to avoid errors.
do {
...
}
while((retry=num.next()).equalsIgnoreCase(again));
// u can also use this, i.e. assign and evaluate at the same time but it's harder to read.

Seeking advice for case switch in loops. my description is below

How do I make my output for Binary to Decimal this: Choice: 1 Binary Number : 2222 INVALID Binary Number
If a user types the binary above 1.
Also, how should I make the default of the switch case not show unless the user inputs the wrong option. Example: They input "HOOPdoop" which is not on the menu screen, the default will output saying that they must try again with the correct input. However, I don't want the default to output when the user inputs "Octal to Decimal" / after the calculation.
here is my code:
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//VARIABLES BEFOR LOOP / FOR LOOP
boolean Loop = true;
String Choice;
//OBJECTS
Scanner input = new Scanner(System.in);
while (Loop == true) {
//MENU
System.out.println("This program will convert...\n" + " \n" + "Binary to Decimal\n" + "Octal to Decimal\n" + "Decimal to Binary\n" + "Decimal to Octal\n" + "or you may Exit");
//ASK
System.out.println("--------------------------------------------");
System.out.println("Which converter would you like to use? or would you like to exit? : ");
Choice = input.nextLine();
//VARIABLES INSIDE LOOP
String binary = "";
int decimal;
String octal;
switch (Choice) {
case "Binary to Decimal":
System.out.print("Enter a binary number: ");
binary = input.nextLine();
if (binary.equals(2)) {
System.out.println("INVALID.");
} else {
System.out.println("Decimal: " + Integer.parseInt(binary, 2));
System.out.println("-----------------------------------------");
}
break;
case "Decimal to Binary":
System.out.print("Enter decimal number: ");
decimal = input.nextInt();
int answer = decimal;
while (answer > 0) {
binary = (answer % 2) + binary;
answer = answer / 2;
}
System.out.println("The binary number = " + binary);
System.out.println("-----------------------------------------");
break;
case "Decimal to Octal":
System.out.print("Enter decimal number: ");
decimal = input.nextInt();
octal = Integer.toOctalString(decimal);
System.out.println("Octal number = " + octal);
System.out.println("-----------------------------------------");
break;
case "Octal to Decimal":
System.out.print("Enter a Octal number: ");
octal = input.nextLine();
System.out.println("Decimal: " + Integer.parseInt(octal, 8));
System.out.println("-----------------------------------------");
break;
case "Exit":
System.out.println("Goodbye!!");
Loop = false;
break;
}
}
}
}```

Writing an application that takes in 2 values and a operator and does the math

I need to write an application which lets the user put in two values and an operator and then calculate it. If the operator is different form +,-,/ or * the application should prompt "Wrong operator input". When it's compiled it should run something like this:
Give me number 1: 5
Give me number 2: 2
Give me an operator: +
Result: 7
The text in bold is userinput.
So far... I've got nothing. I mean I have this:
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1;
int n2;
String o;
System.out.print("Give me number 1: ");
n1 = input.nextInt();
System.out.print("Give me number 2: ");
n2 = input.nextInt();
System.out.print("Give me an operator: ");
o = input.nextLine();
}
}
But that's about it. I have no idea how to proceed. The biggest question I have is: How do I get the users operator to be an actual operator?
Possibly something like the below would suit your needs:
Scanner input = new Scanner(System.in);
System.out.print("Give me number 1: ");
int n1 = input.nextInt();
System.out.print("Give me number 2: ");
int n2 = input.nextInt();
System.out.print("Give me an operator: ");
String o = input.next();
switch (o) {
case "+":
System.out.println(n1 + n2);
break;
case "-":
System.out.println(n1 - n2);
break;
case "*":
System.out.println(n1 * n2);
break;
case "/":
System.out.println(n1 / n2);
break;
default:
System.out.println("Error, invalid operand.");

Categories