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
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 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.
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 3 years ago.
Improve this question
int[] intRange1 = {};
intNum = getValidInt(sIn, "Please enter a whole number: ",
"Invalid response. Only whole numbers are acceptable.", intRange1);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));
// Get an integer within a range from the user
int[] intRange2 = { 10, 50 };
intNum = getValidInt(sIn, "Please enter a whole number between 10 and 50: ",
"Invalid response. Only whole numbers between 10 and 50 are acceptable.", intRange2);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));
}
/*
* making the method I can get it to validate the first part but I can not get
* it to do the part with the range
*/
public static int getValidInt(Scanner sIn, String question, String warning, int[] range) {
boolean valid = false;
int validNumber = 0;
do {
System.out.println("Please enter a whole number: ");
String number = sIn.nextLine();
try {
validNumber = Integer.parseInt(number);
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid response. Only whole numbers are acceptable.");
valid = false;
} // end of try/catch block
} while (!valid);// end of do while
}
Why not just do
int v = SIn.nextInt();
and then catch the exception if it's not an integer. Try the following:
Scanner sIn = new Scanner(System.in);
int r = getValue(sIn, 10, 40);
System.out.println("You entered " + r);
static int getValue(Scanner sIn, int low, int high) {
String msg = "Please enter a number between %d and %d%n";
while (true) {
System.out.printf(msg, low, high);
System.out.print("Enter: ");
try {
int v = sIn.nextInt();
if (v >= low && v <= high) {
sIn.nextLine();//clear input buffer
return v;
}
System.out.printf("Number out of range (%d).", v);
}
catch (InputMismatchException e) {
System.out.printf("Illegal input type (%s)%n", sIn.nextLine());
}
}
}
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 6 years ago.
Improve this question
Problem is I will print all the characters in the keyboard, however everytime it counts 10 the program will stop then press any key to continue.. the sequence will continue.. so far this is what i've done.
public class AsciiDisplay
{
public static void main (String [] args)
{
for (int i = 0; i<=255; i++)
System.out.printf("%d\t%c\n",i,i);
}
}
public static void main(String a[]){
int count = 0;
for (int i = 0; i<=255; i++){
if(count == 10){
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
count = 0;
}else{
System.out.printf("%d\t%c\n",i,i);
count++;
}
}
}
Logic:-
Maintain a counter, increment it every time you print a character, after every 10 increments, it will stop for the user to provide the input, as scanner methods are blocking.
count%10 ==0 means, the number is completely divisible by 10.
public static void main(String[] args){
{
int count=0;
Scanner scanner = new Scanner(System.in);
try{
for (int i = 0; i<=255; i++){
System.out.printf("%d\t%c\n",i,i);
count++;
if((count%10)==0){
System.out.println("Click to continue...");
scanner.nextLine();
}
}
}
finally{
scanner.close();
}
}
}
Though above code is not printing characters by taking input from keyboard.
Maybe, is good solution, beacuse I understood, You want press any key, after 10 numbers was printed starts from 0. Right?
import java.util.Scanner;
public class Test {
private static final Scanner SCANNER = new Scanner(System.in);
public static void main(String a[]) {
int count = 0;
for (int i = 0; i <= 255; i++) {
count++;
if (count % 10 == 0) {
System.out.printf("%d\t%c\n", i, i);
System.out.println("Press \"ENTER\" to continue...");
SCANNER.nextLine();
count = 0;
} else {
System.out.printf("%d\t%c\n", i, i);
}
}
}
}