-
user input- Strings
hey,
i have been trying to work this out for awhile, it compiles with no problems at all but when i run it, it skips over the part that i want to read in the operator.
import java.util.Scanner;
public class calculator
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double total;
System.out.println("Enter your first number: ");
double num1 = keyboard.nextDouble();
//Everything is working fine except for when im reading in the String
//when I run the program it prints out the System.out.print
//but doesn't let me enter my operator is this the way to go about it,
//or do i have to go a completly different way
System.out.println("Enter your chosen operator: ");
String oper = keyboard.nextLine();
System.out.println("Enter your second number: ");
double num2 = keyboard.nextDouble();
if(oper == "+")
{
total = num1+num2;
System.out.println(num1+" + "+num2+" = "+total);
}
else if(oper == "-")
{
total = num1-num2;
System.out.println(num1+" - "+num2+" = "+total);
}
else if (oper == "*")
{
total = num1*num2;
System.out.println(num1+" * "+num2+" = "+total);
}
else if (oper == "/")
{
total = num1/num2;
System.out.println(num1+" / "+num2+" = "+total);
}
}
}
-
The nextInt() and nextDouble() methods read ints and doubles from the input and nothing more; when you type your number you press <enter> which is a character in the input stream and it stays there (those methods don't consume it) so you should add a dummy nextLine() call following the reading of your number to get rid of that <enter> key in your input.
kind regards,
Jos
-
cheers, i'll give that a shot now
-
May not directly be related to your current problem, but if you want to compare string equality, use the equals() method, not == (which compares the String object, not its value)