So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();
Related
I've been trying to make a while loop where I enter in a movie number until the user types 'q' for quit, but every time I enter a valid number, I have to enter it twice before it prompts me with the "Enter movie number" message again. And the break function doesn't work when I wish to leave the loop. I simply wish to enter in the movie number once and break out when I want to.
public class Main {
public static void main(String[] args) {
while(true)
{
System.out.println("Enter in movie number: ");
Scanner input = new Scanner(System.in);
if(!input.hasNextInt())
{
System.out.println("invalid input");
continue;
}
if (Integer.parseInt(input.next()) < 0)
{
System.out.println("invalid no negative numbers");
continue;
}
if(Objects.equals(input.next(), "q"))
break;
}
}
I tried other variations of the while loop, but a similar thing has happened.
I assume your intention is to get one line of input, and if it is a number, process it somehow, and if not check if the user wants to quit.
You've got a couple problems with your program, firstly, you're creating a new Scanner within the while loop, which creates unnecessary overhead. Second, you're trying to get 2 lines of input within your loop, you wait for the user to input an integer, then you try to parse that integer with input.next(). Afterwards, you call input.next() again to check if the user wants to quit. By calling next() twice, you're requiring the user to input 2 lines, causing the issue you were describing.
You can fix this by calling next() once and storing its return value in a variable, then check if it equals q for quit, otherwise you can parse an integer value from it.
Here is working code that applies fixes to these issues:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter in a movie number:");
// Get user input
String input = scanner.next();
// If the input equals q, we break out of the loop
if(input.equalsIgnoreCase("q")) break;
int intInput;
try {
// Get integer input
intInput = Integer.parseInt(input);
} catch(NumberFormatException e) { // Input was not a number
System.out.println("Invalid, must input a number");
continue;
}
if(intInput < 0) {
System.out.println("Invalid, no negative numbers");
continue;
}
}
}
}
Also, a small note, instead of using Object.equals to check if two strings are equal you can just use the equals method inside of the String class like so: str1.equals(str2).
I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}
So im writing a couple methods that require the user to input what hour(1-24) they want. I need however to check whether they enter in an int, and a number between 1-24. The problem is that the scanners are called multiple times if sent to the error statement. I don't know how to do this without having these issues.
public static int getHour(Scanner scan){
int hour=0;
System.out.println("Enter the hour for the showtime (1-24):");
do{
if((!scan.hasNextInt())||((hour=scan.nextInt())<1)||(hour>24)){
System.out.println("Enter a valid number");
scan.next();
} else{
return hour;
}
}while((!scan.hasNextInt())||(hour<1)||(hour>24));
return hour;
}
Ideally it only prompts one time when entering in a not valid input such as a string or int outside of 1-24. but it prompts twice or sometimes once depending on the order of what incorrect input you put in.
Any help would be appreciated, thanks
You're encountering this problem because .hasNextInt() does not advance past the input, and .nextInt() only advances if translation is successful. A combination of loops and if-statements can thus cause confusion as to whether or not the scanner will advance. Here's your method rewritten to have the scanner prompt only once for each bad input:
public int getHour(Scanner scan) {
System.out.printf("%nEnter the hour for the showtime (1-24): ");
while (true) {
input = scan.next();
entry = -1;
try {
entry = (int)Double.parseDouble(input);
} catch (NumberFormatException e) {
// Ensures error is printed for all bad inputs
}
if (entry >= 1 && entry <= 24) {
return entry;
}
System.out.printf("%nEnter a valid number: ");
}
}
I prefer to use an infinite loop in this case, but as that can be dangerous, receive it with caution. Hope this helps!
I am new to the forums so first of all I'd like to say "Hi"! I'm new to Java programming and am trying to make a simple payroll calculating program with three while loops.
The first while loop keeps the program going until the user enters the sentinel "stop". The second and third loops are error traps that ensure the user enters a positive number before continuing.
For some reason, the while loops are not working and I have tried every variation I can think of. The program runs just fine, it just ignores the while loops. If someone could provide some suggestions as to what I'm doing wrong, I'd really appreciate it.
I'm using NetBeans 8.0 IDE if that helps.
Here is my code:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
From what I can see you should make your while (hours<0) to while (hours<0 || hours == null).
This is because... As far as I can see you initialise hours. But no value is input into it. So it remains as null. You could also try changing the while to an if.
Hope this helps. It may be that it does default to 0 but it may be worth for testin purposes to have a console output.
System.out.println(hours);
Befor the while loop to see what your program is reading hours as.
Hope this helps.
The error is that nextDouble does not eat the newline. It skips newlines at the beginning, so in effect only the last nextDouble is concerned.
Best to make a utility function:
Instead of
Hours = sc.nextDouble();
call your own function:
Hours = nextDouble(sc);
private static double nextDouble(Scanner sc) {
double value = -1.0;
if (sc.hasNextDouble()) {
value = sc.nextDouble();
}
sc.nextLine();
return value;
}
Use a small initial letter for field and method names.
Use double/boolean/int instead of the Double/Boolean/Integer as the latter are Object wrappers (classes); the first primitive types.
Call sc.close(); (for good order).
Aside from what has been said above:
sc.nextDouble consumes and returns the next input from the current line. It does not forward the line.
sc.nextLine consumes and returns the input from the current line and forwards to the next line
At the end of your while loop you call Employee = sc.nextLine(); If you follow your logic and only input allowed values, this will always return an empty string as it consumes the current line where your most previously removed double was stored(now empty string "")
When you do something like:
Hours = sc.nextDouble();
you trust the user to enter a double value, and in case the user entered illegal value, a String for example, this line will throw an exception.
You can solve it like this:
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
String hours = sc.nextLine();
try {
Hours = Double.valueOf(hours);
}
catch (NumberFormatException e) {
// keep looping until we get a legal value
Hours = -1.0;
}
}
I am writing a small program (student, though not an assignment for class...but rather a play on a previous assignment). Previously for class, while learning do/while loops, I wrote a program that prompted a user to input integers. When the user typed in 0, it served to get out of the loop, and then outputted the sum of the squares of all the integers typed.
Example output (double spaced for line breaks):
Type an integer: 3
Type an integer: 0
The sum of the squares is 9
My goal now is to take it a step farther. As written, the program crashes if the user types in anything other than an integer. I have been playing around trying to find ways to allow the user to type in other forms of values, without having it crash. In referencing the code below (which is the program at the moment that does crash at any value sans ints), I tried putting in variations of if statements with the console.hasNextInt() method. Yet my attempts in this would cause an error that number in the do/while test may not have been referenced.
Can anyone offer me any tips? It would be appreciated.
public static void userInterface() {
Scanner console = new Scanner(System.in);
int number;
int numberSquared;
int squaredOutput = 0;
do {
System.out.print("Type an integer (0 to quit): ");
number = console.nextInt();
if (number > 0 || number < 0) {
numberSquared = number * number;
squaredOutput += numberSquared;
}
} while (number != 0);
System.out.println("The sum of the squares is " + squaredOutput);
}
The problem is that you are using console.nextInt(); which only takes the next int.
You can use: console.nextLine();.
It would allow your program to accept a string and you can parse it into an Int when necessary:
try {
number=Integer.parseInt(console.nextLine());
} catch(NumberFormatException e) {
System.out.println("Please input an Integer");
}
Just use this function
public static int next(String message) {
while (true) {
System.out.println(message);
try {
return new Scanner(System.in).nextInt();
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
}
There is problem with your code. When you use console.nextInt() and the scanner try to parse every string as Integer. Better solution is to use console.nextLine() and by your own parse it to your number and catch exception that might be thrown if that string is not parsable as any number that you want.
simply it might look like this.
String yourValue = console.nextLine();
try{
int value = Integer.parseInt(yourValue);
}catch(NumberFormatException e){
System.out.println("watch out this value is unparsable!");
}