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.
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 have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}
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();
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}
import java.util.*;
public class June16{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
double b=0;
boolean checkInput = true;
do{
try{
System.out.println("Input b : ");
b = kb.nextDouble();
checkInput = false;
}catch(InputMismatchException ime){
}
}while(checkInput);
}
}
After InputMismatchException is thrown, why my program not prompt for input? :D
From the documentation:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
This is why you end up in an infinite loop if you don't enter a valid double. When you handle the exception, move to the next token with kb.next().
Because if the Scanner.nextDouble() failes it leaves the token on the queue, (which is then read again and again causing it to fail over and over again).
Try the following:
try {
// ...
} catch (InputMismatchException ime) {
kb.next(); // eat the malformed token.
}
ideone.com demo illustrating working example
This is due to the fact that nextDouble will take the decimal number you entered, but there is still a carriage return that you enter that was not read by the scanner. The next time it loops it reads the input, but wait! there is a carriage return there, so... no need to scan anything. It just processes the carriage return. Of course, the program finds that it is not a double, so you get an exception.
How do you fix it? Well, have something that scans whatever leftovers were left by the nextDouble (namely a next()) and then scan the next double again.