Scanner Input validation on a single entry line from user - java

I have a user enter a string of integers and I add them to an ArrayList, however I need to validate each entry is a positive integer. I have tried do/while loops, nested while loops, while with nested if and each runs into its own set of problems.
As an example of my current setup:
User enters for example: 1 2 3 4
pageVar is my Scanner and pageRef is my ArrayList
System.out.println("Please enter the page reference string: ");
while(pageVar.hasNext()) {
if (pageVar.hasNextInt() && pageVar.nextInt() > 0) {
pageRef.add(pageVar.nextInt());
}
else if (pageVar.nextInt() < 0) {
System.out.println("Please enter valid page reference string: ");
}
else if (!pageVar.hasNext()) {
pageVar.close();
}
}
running this my while gets stuck waiting for more input and I cannot determine how to break it.

Every time you call nextInt() you consume a value. Store the value before you compare.
while (pageVar.hasNextInt()) {
int v = pageVar.nextInt();
if (v > 0) {
pageRef.add(v);
} else {
System.out.printf("%d: is not a valid reference value.%n", v);
}
}

//you could try validating the int as it is being entered with a for loop??
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < numbers.length;i++)
{
System.out.println("Enter numbers: ");
numbers[i] = kbd.nextInt();
while(numbers[i] < 0)
{
System.out.println("Please enter a positive integer");
numbers[i] = kbd.nextInt();
}
}
}
}

Related

trying to learn how to error check my code

I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);

Where should I put the variable scanner declaration? "int figureNumber = stdin.nextInt();"

I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...

Why is my try and catch stuck in a loop?

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}

Multiple Scanner Input In For Loop

I've just begun to learn how to program with Java and I had a question with regard to the scanner input. I'm building a little program that simply asks the user for input to create a numerical array. I was wondering if there was a way to check for the numerical input encompassing the for loop, instead of putting a while check on each of my cases in the for loop.
As well, any other comments or suggestions on my code to help me improve and understand what I am doing would be greatly appreciated!
Thank you!
Edit: I'm calling this class from a 'Main' class where I run the program.
import java.util.Scanner; //Import the use of the Java Scanner
public class ArrayBuild { // Open Application
private static Scanner input;
public Double[] anArray;
public static int arrayCount = 0;
public ArrayBuild() { // Constructor for ArrayBuild object
input = new Scanner(System.in);
arrayCount++;
System.out.println("This will be Array: " + arrayCount);
// Array Size Declaration
System.out.println("Enter Array Size: ");
while (!input.hasNextInt()) {
System.out.println("Please enter an integer for Array size!");
input.next();
}
int n = input.nextInt();
anArray = new Double[n]; // Create 'anArray' of size n
//
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0) {
System.out.println("Enter First Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i > 0 && i < (n - 1)) {
System.out.println("Enter Next Number: \n");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i == (n - 1)) {
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
} // End For Loop
}
} // Close Class
One thing you can do to simplify and write clean code is to always separate the repeating code. In your case, inside the for loop, you are only changing the print statement inside the if condition. Take the other code outside like this--
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0)
System.out.println("Enter First Number: ");
else if (i > 0 && i < (n - 1))
System.out.println("Enter Next Number: \n");
else if (i == (n - 1))
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
} // End For Loop

Data verification input in loop

I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}

Categories