Input validation loop in java - java

How would I write an input validation loop and at least one other loop, either counter-controlled or sentinel-controlled. Could you help me how to write any type of code?

final int SIZE = 10;
int [] array = new int[SIZE];
Scanner input = new Scanner(System.in);
for(int i=0; i < array.length; i++)
{
try
{
do
{
System.out.print("Enter Number " + (i+1) + ": ");
array[i] = input.nextInt();
if(array[i] < 0)
System.out.println("Invalid Input - Must be Greater than 0");
}while(array[i] < 0);
}
catch (InputMismatchException e)
{
System.out.println("Invalid Input - Not an Int - Re-Enter");
input.nextLine();
i--;
}
}

Related

Working on a Java Program that utilizes For Loops to separate Even, Odd, and Negative Inputted Integers. Try Catch Handler Gives Out-of-bounds Error? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.
It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.
It then creates an Out of Bounds error for counting these numbers when I enter a String.
I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.
Why is the program affected outside of the loop?
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
boolean ehandle = true;
for (int i = 0; i < twelveInt.length; i++) {
while(ehandle){
try{
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
ehandle = false;
}
catch(Exception e){
System.out.println("Please enter integers only");
// Unsure of what to add here to handle the errors and allow me to reprompt. in.next();
//does not work nor does twelveInt [i] = in.nextInt();
}
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.
This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.
This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.
To avoid this error, you can modify your try catch error as so:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
for (int i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
boolean error = true;
while (error) {
try {
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
error = false;
}
catch (Exception e) {
System.out.println("Please enter integers only");
in.next();
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
}
}
We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).
I hope this helped! Please let me know if you need any further clarifications or details :)
If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.
for (int i = 0; i < twelveInt.length; i++) {
ehandle = true;
while (ehandle) {
try {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt[i] = in.nextInt();
ehandle = false;
} catch(Exception e) {
System.out.println("Please enter integers only");
continue;
}
...

How to loop a user input until integer is entered?

I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Why In while loop user_number not doing check with areEquals method?

While loop not working and dont check with areEquals method new inputs not taking in consideration why?
do {
try {
Scanner number = new Scanner(System.in);
System.out.print("Number : ");
user_number = number.nextInt();
String temp = Integer.toString(user_number);
int[] array = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
array[i] = temp.charAt(i) - '0';
}
while (!areEquals(array)) {
System.out.println("Repeated numbers are not allowed");
System.out.print("Number : ");
user_number = number.nextInt();
}
} catch (InputMismatchException e){
System.out.println("Only integer numbers are allowed !");
ok = false;
}
} while (!ok);
I'm not sure what you're actually asking but
while (!areEquals(array)){
System.out.println("Repeated numbers are not allowed");
System.out.print("Number : ");
user_number = number.nextInt();
}
will lead to an infinite loop if areEquals returns false because you never create a new array from the new input and therefor passing the first value being entered over and over again.

Error when transferring code

I'm writing code for class, and the code works fine when I run it in Dr. Java in class. However when I input it for grading, I get an error that reads:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:247)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
I have no idea what this means, we haven't covered this sort of thing and I am not a very experienced programmer, sorry. My code is as follows;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int indexFirst = 0;
int indexSecond = 0;
int[] first = new int[10000];
int[] second = new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value < 0) {
break;
}
first[indexFirst++] = value;
} while(true);
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value <= 0) {
break;
}
second[indexSecond++] = value;
} while(true);
System.out.println("First Array:");
for (int i = 0; i < indexFirst; i++) {
System.out.print(first[i] + " ");
}
System.out.println("\n");
System.out.println("Second Array:");
for (int i = 0; i < indexSecond; i++) {
System.out.print(second[i] + " ");
}
System.out.println("\n");
for (int i = 1; i < indexFirst; i++) {
if (first[i-1] > first[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
for (int i = 1; i < indexSecond; i++) {
if (second[i-1] > second[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
int[] merged = new int[indexFirst + indexSecond];
int curIdx1 = 0;
int curIdx2 = 0;
for(int mergedIdx = 0; mergedIdx < merged.length; mergedIdx++) {
if (curIdx2 == indexSecond) {
merged[mergedIdx] = first[curIdx1++];
} else if (curIdx1 == indexFirst) {
merged[mergedIdx] = second[curIdx2++];
} else if (first[curIdx1] < second[curIdx2]) {
merged[mergedIdx] = first[curIdx1++];
} else {
merged[mergedIdx] = second[curIdx2++];
}
}
System.out.println("Merged Array:");
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + " ");
}
}
}
If anyone has any input on how to fix this, it would be much appreciated.

Categories