Results 1 to 4 of 4
Thread: user input- Strings
- 04-25-2011, 02:25 PM #1
Member
- Join Date
- Apr 2011
- Posts
- 2
- Rep Power
- 0
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);
}
}
}
- 04-25-2011, 02:30 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,604
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 04-25-2011, 02:40 PM #3
Member
- Join Date
- Apr 2011
- Posts
- 2
- Rep Power
- 0
cheers, i'll give that a shot now
- 04-25-2011, 02:45 PM #4
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,619
- Rep Power
- 5
Similar Threads
-
User Input???
By jonytek in forum New To JavaReplies: 8Last Post: 01-13-2013, 02:52 PM -
Reading strings from the user but dont want to accept numbers ,!
By javanew in forum New To JavaReplies: 1Last Post: 09-24-2010, 07:08 PM -
Sorting printed ArrayList of user inputted strings.
By movsesinator in forum New To JavaReplies: 3Last Post: 04-03-2010, 09:27 PM -
While loop comparing strings from user
By N3VRMND in forum New To JavaReplies: 5Last Post: 10-30-2009, 08:18 AM -
If statements, input, and strings
By evolvepwnz in forum New To JavaReplies: 16Last Post: 10-22-2009, 09:58 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks