Else If Syntax Error in Calculator [duplicate] - java

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.

Related

Why can I not do sum of a and b?

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
boolean aValid = sc.hasNextInt();
System.out.println(aValid);
System.out.println("Enter Second number");
int b = sc.nextInt();
boolean bValid = sc.hasNextInt();
System.out.println(bValid);
if(aValid && bValid){
System.out.println("Sum of number is "+(a+b));
}
else{
System.out.println("Enter integer number");
}
}
}
I try to get input of a and b and validate that a and b are integers. But it takes three input. It gives the sum of the first two numbers and gives the validity of the last two.
you need to place check integer statements before taking input
boolean aValid = sc.hasNextInt();
int a = sc.nextInt();
boolean bValid = sc.hasNextInt();
int b = sc.nextInt();
Running this code makes the error fairly obvious. Some additional debug statements, running the code in debug or testing would also make it clear.
Scanner.nextInt() will throw an exception if it gets a non integer.
Scanner.hasNextInt() on the other hand returns a boolean value to warn you in advance whether it has an integer or not - it does not take the value from the Scanner.
This code has a couple of tiny corrections that will achieve the outcome you stated.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
} else {
sc.next(); //Discard the non-integer input.fr
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}

Input Mismatch Exceptions

I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}

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!

How do I enter values from a loop into an array list?

this is my code:
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
}
}
What I'm trying to do is create a scanner that asks how many values they want to enter and whatever that value is, that's how many times it asks for number input. The problem is after I ask the question how can I add the number to an array list?
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int numOfInput=sc.nextInt();
ArrayList<Integer> array=new ArrayList<Integer>();
while(numOfInput-->0){
array.add(sc.nextInt());
}
}
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
ArrayList<Integer> myArray= new ArrayList<>();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
myArray.add(intValue);
}
}

How to exit this loop?

I want to exit a loop just by pressing Enter. How to do this? Now the loop exits when I enter any nonnumeric value and press Enter. How to exit by entering nothing and pressing Enter?
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
while (scan.hasNextInt()) {
numberIn = scan.nextInt();
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");
This works for me:
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
String input;
while (!(input = scan.nextLine()).isEmpty()) {
numberIn = Integer.parseInt(input);
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");
Try hasNext():
while (scan.hasNext("\\d+")) {
numberIn = scan.nextInt();
numbers.add(numberIn);
}
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
String input;
while (!(input = scan.nextLine()).isEmpty()) {
numberIn = Integer.parseInt(input);
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");

Categories

Resources