Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int enteredValue = -8;
while (enteredValue !=8) {
try {
enteredValue = scanner.nextInt();
if (enteredValue < 0) {
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Invalid interger entered");
enteredValue = -8;
}
break;
}
scanner.nextLine();
return enteredValue;
}
If, as billjamesdev suggests, the point is to get the user to enter a non-negative integer, the code can be made simpler.
None of that magic with -8 is needed, and
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int enteredValue = -8; // just to get loop started
while (enteredValue < 0) {
try {
enteredValue = scanner.nextInt();
if (enteredValue < 0)
System.out.println("Negative integer entered");
}
catch (InputMismatchException ex) {
System.out.println("Invalid integer entered");
scanner.nextLine(); // clear input
}
}
scanner.nextLine();
return enteredValue;
}
Note: rather than throwing an exception on negative input, I chose to just report the error directly, since this allows me to use a more specific message.
A subtlety is that if the exception is thrown, then no assignment to enteredValue can have occurred, and therefore it is still negative, since it is unchanged from the top of the loop.
Using a do-while loop didn't seem to add much to readability, so I left it as a while-loop.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to output "Invalid value" if the MAX_VALUE I have is not an integer. Whenever I run this code, my overall output gets changed. I am wondering how to correctly do this.
import java.util.*;
public class ForLoopPractice {
public static void main(String[]args) {
Scanner scnr = new Scanner(System.in);
final int MAX_VALUE;
System.out.println("Print even values");
System.out.print("Max value: ");
MAX_VALUE = scnr.nextInt();
for (int i=0; i < MAX_VALUE; i++) {
if (i % 2 == 0) {
System.out.println(i + " ");
}
}
while (!scnr.hasNextInt()) {
System.out.println("Invalid value");
scnr.next();
}
System.out.println();
System.out.println("Print a range of values");
System.out.print("First Value: ");
int firstVal = scnr.nextInt();
System.out.print("Last Value: ");
int secondVal = scnr.nextInt();
for (int i = firstVal; i >= secondVal; i--) {
System.out.println(i+ " ");
}
for (int i = firstVal; i <= secondVal; i++) {
System.out.println(i+ " ");
}
}
}
Use a Try-Catch block. Scanner.nextInt() throws InputMismatchException if the input isn't a number.
You can use a function to make sure the program doesn't go forward until the user has selected the proper input.
public static int getValidNumber(){
try{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num;
num = sc.nextInt();
return num;
} catch (InputMismatchException ex){
System.out.println("Invalid Input.");
return getValidNumber();
}
}
You could wrap "MAX_VALUE = scnr.nextInt();" with:
if (scnr.hasNextInt())
It will return true if the next value can be interpreted as an integer.
While taking the input, you can check it by a method isDigit().
If N is a input given by user, check it by System.out.print(Character.isDigit('N'));
The method will provide boolean value.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to solve the next task:
1. Asking the user for a positive integer.
2. If the user adds a negative or a real number or both, the next error message should be displayed on the console: "wrong input".
That is what I have done so far.
Scanner sc = new Scanner(System.in);
System.out.print("Please, add a positive integer! ");
int num = sc.nextInt();
if (num < 0) {
System.out.println("wrong input");
}
Everything works well, except I cannot make sure that the user receives the error message if he/she doesn't type an integer but a real number. In this case, the program goes wrong.
I would appreciate the help.
import java.util.Scanner;
import java.util.InputMismatchException;
public class ScanTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean badInput = true;
int num;
// Keep asking for input in a loop until valid input is received
while(badInput)
{
System.out.print("Please, add a positive integer! ");
try {
num = Integer.parseInt(sc.nextLine());
// the try catch means that nothing below this line will run if the exception is encountered
// control flow will move immediately to the catch block
if (num < 0) {
System.out.println("Please input a positive value.");
} else {
// The input is good, so we can set a flag that allows us to exit the loop
badInput = false;
}
}
catch(InputMismatchException e) {
System.out.println("Please input an integer.");
}
catch(NumberFormatException e) {
System.out.println("Please input an integer.");
}
}
}
}
Occasionally I find it easier to read in a string and then try and parse it. This presumes you would like to repeat the prompt until you get a valid number.
Scanner sc = new Scanner(System.in);
int num = -1;
while (num < 0) {
System.out.print("Please, add a positive integer! ");
String str = sc.nextLine();
try {
num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Only integers are accepted.");
continue;
}
if (num < 0) {
System.out.println("Input is < 0.");
}
}
Read about NumberFormatException here.
When you're using Scanner.nextInt() the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException. To make sure invalid input doesn't stop your program, use a try/catch to handle the exception:
int num;
try {
num = sc.nextInt();
// Continue doing things with num
} catch (InputMismatchException e) {
// Tell the user the error occured
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Problem
Method asks user for an integer value.
Pass the value into a loop to ensure it is a positive number.
Add a in.nextline to ensure the value don't overrun into next line of code. -
Return integer value.
private static int getIntFromUser(String aa) {
int aaa = 0;
while (true && aaa <= 0) {
try {
System.out.println(aa + ": ");
aaa = in.nextInt();
if (aaa <= 0) {
System.out.println("Please enter a positive number.");
}
} catch (Exception e) {
System.out.println("Please enter an integer: ");
in.next();
}
}
in.next();
return aaa;
}
Question
Try/Catch with while loop can't work ?
Tested it myself, it returns aaa properly (after removing in.next() at the bottom of the method and replacing it with in.nextLine()). When you do a return call, you need to send it somewhere. Such as System.out or to a variable like int x = getUserFromInput("test: ");
public class Tester {
private static Scanner in = new Scanner(System.in);
private static int getIntFromUser(String aa) {
int aaa = 0;
while (true && aaa <= 0) {
try {
System.out.println(aa + ": ");
aaa = in.nextInt();
if (aaa <= 0) {
System.out.println("Please enter a positive number.");
}
} catch (Exception e) {
System.out.println("Please enter an integer: ");
in.next();
}
}
in.nextLine();
return aaa;
}
public static void main(String[] a) {
System.out.println(getIntFromUser("test123"));
}
}
Output
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
How can I access a variable from inside a do-while loop in Java?
The code below writes out a value until the value entered is not is between 0 and 10.
Here is my code :
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int total +=0;
}while (a>0 && a<10);
System.out.println("Loop Terminated");
System.out.println("The total is : "+total);
}
}
The loop continues to ask for input so long as the input is between 0 and 10. Once some other number is entered the loop terminates and displays the total of all inputted numbers.
try like (declare the variable a outside the loop):
int a = -1;
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
}while (a>0 && a<10);
To access a variable beyond the loop, you need to declare/initialize it outside of the loop and then change it inside the loop. If the variable in question wasn't an int, I would suggest that you initialize it to null. However, since you can't initialize an int variable to null, you'll have to initialize it to some random value:
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
int a = 0; //create it here
do {
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
} while (a>0 && a<10);
System.out.println("Loop Terminated");
// do something with a
}
}
NOTE: If you simply declare the variable before the loop without initializing it (as per #Evginy's answer), you'll be able to access it outside the loop but your compiler will complain that it might not have been initialized.
try this
Scanner in = new Scanner(System.in);
int a;
do {
System.out.println("Enter a number between 0 an 10");
a = in.nextInt();
} while (a > 0 && a < 10);
System.out.println("Loop Terminated");
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
private void addMember() {
while (true) {
String mNum = readLine("Please enter a membership number: ");
if (mNum == null) break;
Integer mNumAsInteger = Integer.parseInt(mNum);
String mName = readLine("Please enter the member's name: ");
members.put(mNumAsInteger, mName);
}
}
private Map<Integer, String> members = new HashMap<Integer, String>();
The purpose of the code is to keep adding members until user enter a blank input.
Is there a way to change the first line to something like
Integer mNum = readInt("Please enter a membership number: ");
And somehow detects a blank input?
You can use a Scanner, which provides a simpler API for reading from a stream.
private static void addMember() {
Scanner sc = new Scanner(System.in).useDelimiter("\n");
while (true) {
try {
System.out.println("Please enter a membership number: ");
int mNum = sc.nextInt();
System.out.println("Please enter the member's name: ");
String mName = sc.next();
members.put(mNum, mName);
} catch (Exception e) {
break;
}
}
}
http://ideone.com/jhN3j
Not sure if the best, but maybe what you are looking for:
try{
Integer mNum = Integer.parseInt(readLine("Please enter a membership number: "));
}catch (NumberFormatException e){
System.out.println("Error parsing membership number");
}
You might try this class: http://www.cs.kzoo.edu/GridPkg/GridPkgClassDocumentation/edu/kzoo/util/ValidatedInputReader.html