Java Calculator Switch Issue - java

I incorporated a couple different methods I've seen on here. Does anyone know how to fix this problem I am having? When you use this code, It asks for you to enter the mathematical operator, BUT when I do if I enter +9 or -%, it will still work and use the first symbol. I want it to give an error if someone inputs */ instead of just *. I even tried switching the case to numbers (ie case 1:) and it will do the same thing if I set addition to 1 and if I enter 15, it will read the one and do addition. Any ideas?
import java.util.Scanner;
public class javacalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double num1, num2, answer;
char userOperation;
System.out.print("Enter your full name: ");
String userName = input.nextLine();
System.out.println("+ Addition");
System.out.println("- Subtraction");
System.out.println("* Multiplication");
System.out.println("/ Division");
System.out.println("% Modulus");
System.out.println("\n");
System.out.print("Enter mathematical operator e.g. + for Addition: ");
userOperation = operation.next().charAt(0);
boolean invalidOperator = false;
switch (userOperation) {
case '+':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 + num2;
System.out.print(num1 + " + " + num2 + " = " + answer);
break;
case '-':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 - num2;
System.out.print(num1 + " - " + num2 + " = " + answer);
break;
case '*':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 * num2;
System.out.print(num1 + " * " + num2 + " = " + answer);
break;
case '/':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 / num2;
System.out.print(num1 + " / " + num2 + " = " + answer);
break;
case '%':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 % num2;
System.out.print(num1 + " % " + num2 + " = " + answer);
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}

Let us break this down: operation.next().charAt(0);
operation.next() -> Gives you full input string
.charAt(0); -> returns the first character of the full input string
So anything we enter +9 or */ -> it returns the first element.
Now let's handle this case:
String o = operation.next(); // here is complete input
if(o.length()!=1){
userOperation = 0; //if length of input is not 1 we set custom value
}else{
userOperation = o.charAt(0); //get and set the first and only element
}
Hopefully it helps!

Related

validating char user input loop

I'm writing a simple calculator program, the user inputs two integers and a symbol (+ - * etc) which represents the operation (add, subtract, multiply, etc) to be applied to the integers and the program calculates what they asked.
I have a do-while loop to continually ask for input if the input does not match the given symbols.
I've tried comparing them but I'm unsuccessful and very uncertain on what to do
CODE:
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String a, b, c, userInput;
char choice, plus, minus, times;
System.out.print(First Integer: --> ");
num1 = scan.nextInt();
System.out.print(Second Integer: --> ");
num2 = scan.nextInt();
a = "+";
b = "-";
c = "*";
plus = a.charAt(0);
minus = b.charAt(0);
times = c.charAt(0);
do {
System.out.print("Choose + - or *");
userInput = scan.Next();
choice = userInput.charAt(0);
} while(choice != '+' || choice != '-' || choice != '*');
switch(choice) {
case 1:
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case 2:
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case 3:
product = num1 ' num2;
System.out.println("Product is " + product);
break;
}
There were some errors in your code, I have tried to rectify them.
Take a look,
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String userInput;
char choice, plus, minus, times;
System.out.println("First Integer: --> ") ;
num1 = scan.nextInt();
System.out.println("Second Integer: --> ") ;
num2 = scan.nextInt();
plus = '+';
minus = '-';
times = '*';
do {
System.out.println("Choose + - or *") ;
userInput = scan.next();
choice = userInput.charAt(0);
}while(choice != '+' && choice != '-' && choice != '*');
switch(choice) {
case '+':
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case '-':
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case '*':
product = num1 * num2;
System.out.println("Product is " + product);
break;
default :
System.out.println("Wrong Choice!");
break;
}
}
}

Not getting the expected output from the do-while loop

In this calculator program when I type in any other incorrect answer for the operator such as a number or a letter instead of +, -, *, / it shows the "wrong only operators" message but even when I put in the correct operator the same message still shows up.
How can the program not show the wrong message when I type in the correct symbol.
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner (System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
do
{
operator = scan.next().charAt(0);
System.out.println("Wrong only operators. ");
scan.nextLine();
}
while(operator != '+' && operator != '-' && operator != '*' && operator != '/');
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
In your case it is better to use a while loop instead of a do while.
Since you are using a do while loop : that statement is being executed at least once, not matter whether the operator is correct or not.
You can add a condition there to stop it from executing but a better way is to use while loop
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner(System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
operator = scan.next().charAt(0);
while(operator != '+' && operator != '-' && operator != '*' && operator != '/')
{
System.out.println("Wrong only operators. ");
operator = scan.next().charAt(0);
scan.nextLine();
}
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}

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;
}
}
}
}```

Cannot resolve method append(int)

The goal of the project is to create a calculator which will let the user choose which operation to use, which will then be solved and added to a linked list. The last option is to see the history which are past answers or solutions.
I'm quite new and this is a project I'm really trying to finish on my own but I have researched and still can't seem to quite understand what or how to fix. Please explain to me so that I can understand better! Also please comment on the design or flow of my code. Thanks!
import java.util.Scanner;
import java.util.LinkedList;
public class projectOne {
public static void main(String[] args) {
int one = 0;
int two = 0;
int ans = 0;
int selection = 0;
Scanner scanner = new Scanner(System.in);
LinkedList l = new LinkedList();
do{
System.out.println("\nSelect an option: \n1. Addition \n2. Subtraction \n3. Multiplication \n4.Division \n5. See History");
selection = scanner.nextInt();
/* if (selection >= 1 && selection <= 4) {
System.out.println("\nEnter two numbers to be used in relevant calculation: ");
one = scanner.nextDouble();
two = scanner.nextDouble();
}
*/
switch(selection) {
case 1:
System.out.println("Performing Addition. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " + " + two + " = " + (one + two));
ans = one + two;
l.append(ans);
break;
case 2:
System.out.println("Performing Subtraction. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " - " + two + " = " + (one - two));
ans = one - two;
l.append(ans);
break;
case 3:
System.out.println("Performing Multiplication. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " * " + two + " = " + (one * two));
ans = one * two;
l.append(ans);
break;
case 4:
System.out.println("Performing Division. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " / " + two + " = " + (one / two));
ans = one / two;
l.append(ans);
break;
case 5:
System.out.println("History: \n" + l);
break;
}
} while(selection != 6);
}
}
LinkedList does not have method append, you can use add, addLast.
Also, please avoid using raw type, use LinkedList<Integer> instead.

Java scanner requiring multiple inputs

I'd like to ask a question about my code.
I apologize for the inefficiency and the messiness of it, I am still trying to learn java.
System.out.println("Please choose the number corresponding to the operation: ");
System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");
if (sc.nextInt() == 5) {
System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
} else if (sc.nextInt() == 3) {
System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));
} else if (sc.nextInt() == 4) {
System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));
} else if (sc.nextInt() == 1) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Addition: " + (n1 + n2) + "/" + d);
} else if (sc.nextInt() == 2) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Subtract: " + (n1 - n2) + "/" + d);
}
else if (sc.nextInt() == 6 ) {
System.exit(0);
}
}
}
When I run the program, the first if statement gets by fine, as I only have to input the number 5 one time. However as you can see from the second else if statement which is the number 3 requires two inputs, I have to enter it two times before the next line comes up. The third else if statement which is the number 4 requires 3 inputs before the next line shows up, and so on with each successive else if statement. I'm sorry if I am not explaining this properly, Does anyone have any idea why this is happening?
Change your code to:
int input = sc.nextInt();
sc.nextLine();
if (input == 5) {
and all other if (sc.nextInt()...)also.
nextInt will consume your input. So if you come to the second if the input is alredy consumed by the first if .
nextLine is nessesary to consume the <ENTER> after the int value.
Try to use switch statement.
package practice;
import java.util.Scanner;
public class Stack{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE 2 NUMBERS");
int num1=sc.nextInt();
int num2=sc.nextInt();
System.out.println("ENTER THE CHOICE");
int choice='0';
while(choice!=6)
{
choice=sc.nextInt();
System.out.println(choice);
switch(choice)
{
case 1:
int add=num1+num2;
System.out.println("Addition:"+add);
break;
case 2:
System.out.println("Subtract:");
break;
case 3:
System.out.println("Multiply:");
break;
case 4:
System.out.println("Divide:");
break;
case 5:
System.out.println("Your first fraction is:");
System.out.println("Your second fraction is:");
break;
case 6:
System.exit(0);
break;
default:
System.out.println("LOSER");
break;
}
}
sc.close();
}
}

Categories