Java 4 operator calculator using switch not working - java

When i run it, nothing happens. Whats weird to me is how the systemoutprintln asking what you want to do doesnt work either. The scanner is called earlier in it by the way. If im doing something completely wrong please tell me :) Any help would be tremendous.
Scanner scanner3 = new Scanner(System.in);
String operator = scanner3.nextLine();
System.out.println("What do you want to do? (add, subtract, multiply, or divide?)");
switch (operator){
case "add": System.out.println("Enter number one ");
Scanner scanner4 = new Scanner(System.in);
double addnum1 = scanner4.nextDouble();
System.out.println("Enter number two ");
Scanner scanner5 = new Scanner(System.in);
double addnum2 = scanner5.nextDouble();
System.out.print("the answer is: ");
System.out.println( addnum1 + addnum2);
break;
case "subtract": System.out.println("Enter number one");
Scanner scanner7 = new Scanner(System.in);
double subnum1 = scanner7.nextDouble();
System.out.println("Enter number two ");
Scanner scanner8 = new Scanner(System.in);
double subnum2 = scanner8.nextDouble();
System.out.print("the answer is: ");
System.out.println( subnum1 - subnum2 );
break;
case "multiply": System.out.println("Enter number one");
Scanner scanner9 = new Scanner(System.in);
double mulnum1 = scanner9.nextDouble();
System.out.println("Enter number two ");
Scanner scanner10 = new Scanner(System.in);
double mulnum2 = scanner10.nextDouble();
System.out.print("the answer is: ");
System.out.println( mulnum1 * mulnum2 );
break;
case "divide": System.out.println("Enter number one");
Scanner scanner11 = new Scanner(System.in);
double divnum1 = scanner11.nextDouble();
System.out.println("Enter number two ");
Scanner scanner12 = new Scanner(System.in);
double divnum2 = scanner12.nextDouble();
System.out.print("the answer is: ");
System.out.println( divnum1 / divnum2 );
break;
}

the first printing
System.out.println("What do you want to do? (add, subtract, multiply or divide?)");
was after the
.nextLine()
so your program expects the input before printing the first message.
you can use same scanner for all cases, much better and cleaner code.
Scanner scanner_all = new Scanner(System.in);
System.out.println("What do you want to do? (add, subtract, multiply or divide?)");
String operator = scanner_all.nextLine();
switch (operator){
case "add":
System.out.println("Enter number one ");
double addnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double addnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( addnum1 + addnum2);
break;
case "subtract":
System.out.println("Enter number one");
double subnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double subnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( subnum1 - subnum2 );
break;
case "multiply":
System.out.println("Enter number one");
double mulnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double mulnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( mulnum1 * mulnum2 );
break;
case "divide":
System.out.println("Enter number one");
double divnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double divnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( divnum1 / divnum2 );
break;
}

Related

How to perform mathematical operation on integers/double extracted from input.nextInt() / input.nextDouble()?

I am asking the user to write 2 integers and I need to perform some mathematical operations with them. How can I do it?
In this case, for example, I am selecting the "add" operation, I am writing the integers 2 and 3, and I would like to have "5" as the result.
PS: I need to use the "Switch" method.
Output terminal
Best regards.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("List of operations: add subtract multiply divide alphabetize");
Scanner input = new Scanner(System.in);
System.out.print("Enter an operation: ");
String type_operation = input.nextLine().toLowerCase();
if ((new String(type_operation).equals("add")) ||
(new String(type_operation).equals("substract")) ||
(new String(type_operation).equals("multiply")) ||
(new String(type_operation).equals("divide")) ||
(new String(type_operation).equals("alphabetize"))) {
switch (type_operation) {
case "add":
System.out.print("Enter two integers: ");
int integers_1 = input.nextInt();
System.out.println(integers_1);
case "substract":
System.out.print("Enter two integers: ");
int integers_2 = input.nextInt();
break;
case "multiply":
System.out.print( "Enter two doubles: ");
double integers_3 = input.nextDouble();
break;
case "divide":
System.out.print("Enter two doubles: ");
double integers_4 = input.nextDouble();
break;
case "alphabetize":
System.out.print("Enter two Strings: ");
String integers_5 = input.nextLine();
break;
}
else {
System.out.println("Invalid value.");
}
}
}

Ending while loop with string not working

I have a problem with trying to end this while loop. When it runs, typing "exit" for the name part doesn't seem to register and the code continues as if "exit" was a name typed in. What I intended to happen is for "exit" to be typed in so that the loop can end. Any help? Here is the code for the class:
import java.util.*;
import java.io.*;
public class BankTest {
public static void main(String args[]) {
List<BankAccount> bank = new ArrayList<BankAccount>();
Scanner scan = new Scanner(System.in);
//enter into list the accounts and end with exit typed in
String name = "";
while (name.contains("exit")==false) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
//find highest account amount
double largestMon = bank.get(0).getBalance();
String largestPer = bank.get(0).getName();
for (int i=0;i<bank.size();i++) {
double compare = bank.get(i).getBalance();
if (compare>largestMon) {
largestMon = compare;
largestPer = bank.get(i).getName();
}
}
System.out.println(largestPer+" has the largest account with $");
}
}
I've already tried switching between != and equals() compare the strings.
Change while (name.contains("exit")==false) to while(true)
and add line if (name.equals('exit')) break; after name = scan.nextLine();
First of all you could change
name.contains("exit")==falseinto !name.contains("exit")
A better solution would be to use a while true loop and break if the name variable is equal to "exit"
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
Notice that in cases like this you shouldn't use .contains() or .equals but rather .equalsIgnoreCase()
This should work
while(true){
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
Modify your while loop as follows:
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

Stopping a repeating Println in a while loop, BlueJ

Below is the code I have so far, it is a calculator for my computer science class. The problem I am having is that on the second run of the program the System.out.print("Would you like to perform a calculation? (y/n) "); runs twice instead of once. I have already turned in the project, but I would like to know why it does this and how, in my future programs, I can fix it. I'll post the rest of the code below.
I appreciate all of your help, I credit the "A" that I got on it to all of you. Thanks!
/**
* A calculator with multiple functions.
* #author ()
* #version (version 2.1)
*/
import java.io.*;
import java.util.Scanner;
public class Calc
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
String cont = "", funct = "";
double fnum = 0, snum = 0, answer = 0;
while(true)
{
System.out.print("Would you like to perform a calculation? (y/n) ");
cont = reader.nextLine();
if (cont.equalsIgnoreCase("y"))
{
System.out.println("What function would you like to do?");
System.out.println("+?");
System.out.println("-?");
System.out.println("*?");
System.out.println("/?");
funct = reader.nextLine();
if (funct.equals("+"))
{
System.out.println("Simple addition calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum + snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("*"))
{
System.out.println("Simple multiplication calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum * snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
}
else if (cont.equalsIgnoreCase("n"))
{
break;
}
}
}
}
In all of your function conditions inside the loop, you are using reader.nextDouble(). This will only read the number (e.g "8") input not the new line (the enter) which is entered by the user after the number.
Following code for the minus(-) function will not print "Would you like to perform a calculation? (y/n) " twice as the new line is already read. Here reader.nextLine() is used instead of reader.nextDouble(). reader.nextLine() will read the whole line not only the number.
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = Double.parseDouble( reader.nextLine());
System.out.println("Enter second num: ");
snum = Double.parseDouble( reader.nextLine());
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
You need to consume the newline character after you call nextDouble() and before the next nextLine() to prevent nextLine() consume the newline character. Otherwise funct = reader.nextLine(); will take the new line character as input and not wait for any more user input, which results in the repeat.
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble(); // consume the new line character
reader.nextLine();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
Try adding this reader.nextLine(); before the while loop ends, as mentioned below. This will clear the screen buffer.
else if (cont.equalsIgnoreCase("n"))
{
break;
}
reader.nextLine();
}
Hope this helps,
Basically what is happening is when you are using the reader.nextLine() method, there is still a newline character left in the buffer, which is picked up when calling nextLine(). So it's making an extra run with the newline character. If you run your program with newline as the input even for the first time, it will loop without doing anything. So, you just need to clear out the buffer before going into your while loop.

Else If Syntax Error in Calculator [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been trying to make a basic calculator, but the thing is every time I use if else, it either says I have to remove it due to syntax error or the green underline thing shows up and it says dead code. Could someone help me?
import java.util.Scanner;
public class additionCalculator {
public static void main(String[] args) {
int addresult;
int subtractresult;
int divideresult;
int multiplyresult;
String addition = null;
String subtraction = null;
String division = null;
String multiplication = null;
Scanner reader = new Scanner(System.in);
System.out.println("Do you want to do subtraction, division, multiplication, or addition?");
String i = reader.next();
if(i == addition) {
Scanner additioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int add1 = reader.nextInt();
Scanner additioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int add2 = reader.nextInt();
addresult = add1 + add2;
System.out.println("The sum is " +addresult);
} else if (i == multiplication) {
Scanner multiplicationcalc = new Scanner (System.in);
System.out.println("Enter a number");
int multiply1 = reader.nextInt();
Scanner multiplcationcalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int multiply2 = reader.nextInt();
multiplyresult = multiply1 * multiply2;
System.out.println("The product is " +multiplyresult);
} else if (i == division) {
Scanner divisioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int div1 = reader.nextInt();
Scanner divisioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int div2 = reader.nextInt();
divideresult = div1 * div2;
System.out.println("The product is " +divideresult);
} else if (i == subtraction) {
Scanner subtractioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int subtract1 = reader.nextInt();
Scanner subtractioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int subtract2 = reader.nextInt();
subtractresult = subtract1 - subtract2;
System.out.println("The difference is " +subtractresult);
}
}
// Addition calculator
// Scanner reader = new Scanner(System.in);
// System.out.println("Please enter a number.");
// int i = reader.nextInt();
// Scanner reader2 = new Scanner(System.in);
// System.out.println("Please enter another number.");
// int j = reader2.nextInt();
// sum = i + j;
// System.out.println("The sum of the two numbers is " +sum);
}
You should be using string comparison function from java.lang.String.
Note:
== tests for reference equality.
.equals() tests for value equality.

Categories

Resources