Ive got a problem.I 'm new to Java,I've started today:D) ..I've programmed before so I know it little bit,but I am new to Java. Here is my code: `
public class Tutorial {
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.nextLine();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
}`
It wants from me 2 numbers,I write them and them it writes "Choose the operation" and its over.No more inputs.Thank you very much :)
Your problem is simple.
Just replace the code with next() instead of nextLine().Effectively, the line your code is returning is receiving is a blank line. Hence when it reaches the conditional statement it has an empty string and terminates.
next()
Finds and returns the next complete token from this scanner.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
Your code should be fixed by a simple change.
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.next();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
Scanner#nextDouble() consumes only the next token as a double from the input. It does not consume the new line you typed using the Enter on the keyboard while entering the two numbers. When the execution reaches operacia=in.nextLine();, this new line is consumed, never allowing the user a chance to type the operating string.
To solve this, you need to read the whole line using Scanner#nextLine() and convert it to a double:
String input = in.nextLine();
num1 = Double.parseDouble(input);
input = in.nextLine();
num2 = Double.parseDouble(input);
I believe the in.nextLine(); operation is reading only to the end of the line where you input 2 numbers. If you want your program to only consider the next line, you have to clear the current one first.
Try this, it should work:
System.out.println("Choose the operation");
in.nextLine(); //clear the current line
operacia=in.nextLine();
Related
It's my first time posting some topic on this website, and running on a problem that I can't get over it. The following problem that I'm stunning into is as followed:
When the total calculation of the above decimal numbers meets a specific target amount, print: "Congratulations" if not, print:"Calculation error", after they input the string word: "Ready". when a user inputs a string called: "I Quit!", the application will exit and prints: "Quitter".
Here is the Java code that I currently have:
public static void goal(double targetAmount) {
Scanner sc = new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double input= sc.nextDouble();
total += input;
}
String inputString = sc.next();
}
I'm looking forward to see your response. Hope I've formulate my question properly?
I think the problem is the input you read using scanner.next(), because scanner.next() reads the input till the next blank character. Which means it will just read I when you enter I Quit!.
Printing the output of the variable input shows the problem:
public static void main(String[] args) {
salarisdoel(100);
}
public static void salarisdoel(double targetAmount) {
Scanner scanner= new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double inputMoney= scanner.nextDouble();
total += inputMoney;
}
String input = scanner.next();
System.out.println(input);//print to check what was read from the console
switch (input) {
case "I Quit!":
System.out.println("Quitter");
break;
case "Ready":
if (total>= targetAmount) {
System.out.println("Congratulations");
} else {
System.out.println("Calculation Error");
}
break;
default:
System.out.println("Something went wrong. Try again!");
break;
}
}
If you use a string without a blank space for quitting (e.g. "I_Quit!") it will work.
You can use System.exit() to exit the program.
case "I Quit!":
System.out.println("Quitter");
System.exit();
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
I am new to java and doing an assignment.
I have to request 3 inputs from the user and I have validation.
If I do it with only one instance of the scanner I get all messed up.
If I use three instances with a bit of workaround my code works.
Only I guess this is not best practice.
I have been reading a bit the manual regarding the scanner, but cannot understand the problem
Thanks
enter code here
Scanner input=new Scanner(System.in);
Scanner input2=new Scanner(System.in);
int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;
System.out.print("\n Please enter a number: ");
while(!input.hasNextInt()){
System.out.println("***** Error: the char inserted is not a number! *****");
String input_wrong=input.next();
System.out.print("\n Please enter a number: ");
}
input_integer=input.nextInt();
System.out.print("\n Please enter a double: ");
while(!input.hasNextDouble()){
System.out.println("***** Error: the char inserted is not a double! *****");
String input_wrong=input.next();
System.out.print("\n Please enter an double: ");
}
input_double=input.nextDouble();
System.out.print("\nPlease enter a string: ");
input_string=input.nextLine();
So I had two create 3 scanner instances and also to use a string to assign the wrong input in the while cycle to the able to prompt again.
Any suggestion?
I am sure there is a better way but I would try to understand..
Thanks!
I'm not exactly sure I understand what problem you're having, but scanner has some strange behaviors which are not immediately obvious. For instance, if you type "1234bubble" then press enter, then nextInt() will return 1234 and the next nextLine() will say "bubble". That is usually not desired behavior for inputs like this because "1234bubble" is not an integer and should have failed when the user pressed enter.
For that reason, I typically only use the function nextLine(). Then, I just process the data manually using functions like Integer.parseInt(..). That way, I can guarantee that I'm processing the whole line in a clear and obvious manner, unlike other techniques which create confusing code.
Here's how I would have written your program:
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main
{
static Random rand = new Random();
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
int input_integer = 0;
double input_double = 0.0;
String input_string = "";
double value = 0;
while (true)
{
System.out.print("Please enter an integer: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into an integer
input_integer = Integer.parseInt(text);
// Turning it into an int succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an int failed.
System.out.println("***** Error: the text inserted is not an integer! *****");
}
}
while (true)
{
System.out.print("Please enter a double: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into a double
input_double = Double.parseDouble(text);
// Turning it into an double succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an double failed.
System.out.println("***** Error: the text inserted is not a double! *****");
}
}
System.out.print("Please enter a string: ");
input_string = input.nextLine();
// This is done automatically when the program stops, but it's
// a good habit to get into for longer running programs.
input.close();
}
}
package pkgswitch;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
double subtotal = 0.0;
Scanner sc = new Scanner(System.in);
outerloop:
while(0==0){
System.out.print("Enter subtotal: ");
if (sc.hasNextDouble())
{
subtotal=sc.nextDouble();
}
else
{
sc.nextLine();
System.out.println("Error!");
continue outerloop;
}
}
}
}
I'm working with learning how to catch exceptions. (I know about the try / catch)
Question:
How does scanner have more double tokens when it has just been initialized with no input
How does scanner have more double tokens when it has just been initialized with no input?
Your code doesn't initialize the scanner with "no input". It initializes it with System.in.
What actually happens is that sc.hasNextDouble() attempts to read and buffer characters from the input stream ... blocking if the user hasn't typed them yet. When the method has enough characters to determine if it has a valid double token, it returns true ... or false.
By the way:
while (0 == 0) {
is silly. Please don't do it. It causes the reader to waste his / her time:
figuring out what the code is really doing, and
wondering whether the author doesn't understand basic Java, or has been using illegal substances while coding ... :-)
System.in is an InputStream. From javadoc, read "blocks until input data is available, the end of the stream is detected, or an exception is thrown".
It doesn't. Check this out: I've added two print statements to your code. If you run this, you'll see that the method hasNextDouble() does not return anything until after you've entered a value. So if you type a double, then hasNextDouble() will return true, and the program will set the subtotal to that value (also, not sure, but it seems to me you may want to add to subtotal instead of setting it's value).
public static void main(String[] args) {
double subtotal = 0.0;
Scanner sc = new Scanner(System.in);
outerloop:
while(0==0){
System.out.print("Enter subtotal: ");
if (sc.hasNextDouble())
{
System.out.println("has next double."); /* added */
subtotal=sc.nextDouble();
System.out.println("read double: "+subtotal);
}
else
{
System.out.println("no next double"); /* added */
sc.nextLine();
System.out.println("Error!");
continue outerloop;
}
}
}
first of all it is nice to have while(true) than while(0==0) .When It prints "Enter Sub total" you can give a double (ex 3.0).Then sc.hasNextDouble() becomes true and whatever the code in if statement runs.If you give a input which is not double(ex 'k') then sc.hasNextDouble() becomes false and whatever in the else is running.
public class Calculator
{
public static void main(String[] args)
{
boolean isValid = false;
Scanner myScanner = new Scanner(System.in);
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = myScanner.next();
while (isValid == false)
{
System.out.print("Enter Subtotal: ");
if (myScanner.hasNextDouble())
{
double sobTotal = myScanner.nextDouble();
isValid = true;
}
else
{
System.out
.println("Hay! Entry error please enter a valid number");
}
myScanner.nextLine();
}
}
}
Hi, im new to java, as usual im trying out a few things in the Scanner Class.
is there a way to see the input of the scanner?
Cuz i have a problem here with the code above as you'll see. this is the output of my console window after i entered wrong data. instead of numbers i entered KKK so can somebody explain me why i got this error message 2 times?
"this is the console"
Customer Type? (C/R) R
Enter Subtotal: KKK
Hay! Entry error please enter a valid number
Enter Subtotal: Hay! Entry error please enter a valid number
Enter Subtotal:
Change your code as follows.
boolean isValid = false;
Scanner myScanner = new Scanner(System.in);
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = myScanner.next();
while (!isValid)
{
System.out.print("Enter Subtotal: ");
if (myScanner.hasNext())
{
try
{
double sobTotal =Double.parseDouble(myScanner.next());
isValid = true;
}
catch(Exception e)
{
System.out.println("Hay! Entry error please enter a valid number");
}
}
}
When you use Scanner.nextDouble(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string.
The problem is you're calling scanner.nextdouble() which will work fine if and when there is a double in the input. When there is not a double in the input your input that was "KKK" is ignored by the call to nextDouble() and your error message is displayed then when you call nextLine() that same input "KKK" is still there waiting wo when you loop back throught the while the "KKK" is then passed back to your program and since it is still not a double you get the repeated error message.
Try this:
boolean isValid = false;
Scanner myScanner = new Scanner(System.in).useDelimiter("\\n");
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = myScanner.next();
while (!isValid)
{
System.out.print("Enter Subtotal: ");
if (myScanner.hasNextDouble())
{
double sobTotal = myScanner.nextDouble();
isValid = true;
}
else
{
System.out.println("Hay! Entry error please enter a valid number");
if(myScanner.hasNext()){
myScanner.next();
}
}
}
That will consume the invalid input of "KKK" and let the program continue properly.
I think the real problem is that you have some obfuscation in your loop structure that makes it hard to understand the in and out conditions of the scanner with each iteration of the loop.
Heres what is really happening. We enter the loop with one token in the Scanner which is not a double. We ask is there a double next in the scanner with hasNextDouble(), which since the one token can not be converted to a double, this returns false. We report an error and isValid remains false. After the branch we call scanner.next() and consumer our non double token. We renter the loop since isValid remains false. We again ask if there is a double next in the Scanner. Now the scanner is empty, since we consumed out token, and this call returns false, so we report another error. Now we call scanner.next() again. Since the scanner is now empty, and scanner.next() implements synchronous message passing (I/O), we now block until the scanner recieves a new token, so your program will stall until you input a new token. Try puting in more into your console. You would probably repeat the loop and see another error.
What you want to accomplish is with each loop, consume a token. If that token is a double, accept the input and continue, if not report an error and repeat. Try something like this instead, it should present a more clear picture of what the scanner is doing every loop.
public class Calculator
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = scan.next();
Double test = null;
do{
try{
test = scan.nextDouble();
}catch (InputMismatchException ime){ //will be thrown if the token we input is not a double
System.err.println("Error Message");
}
}while(test == null);
}
}
Notice i use the wrapper class Double not the primative double. This is so that I can set the double to null, since Double is an Object and not a primitive.