Hello all I am trying to validate a set of inputs from a user, where it does not accept blanks, letter, letter with numbers, and numbers out of the range 0=100.
It goes fine except but when I input greater than 100, for example 150, it will catch and tell you to try again but when a letter is typed on the second prompt, it fails. And it'll only fail if the sequence of input is int is greater than 100 is input and the second input is a letter. I have a feeling it is the logic but I cant figure out exactly on which part.
It errors right on the line when arrayInt is declared (3rd set of while loop from validateUserInput method)
public static void main(String[] args) {
// Ask for user input
Scanner input = new Scanner(System.in);
//declare an array with index of 5
int array[] = new int[5];
//loop to prompt user to input 5 test scores, each of which are stored in array
for (int i = 0; i < array.length; i++){
System.out.println("Enter score " + (i+1) + ": ");
//array[i] = Integer.parseInt(input.nextLine());
String arrayInput = input.nextLine();
arrayInput = validateUserInput (arrayInput);
array[i] = Integer.parseInt(arrayInput);
}
//call method to display test scores
displayTestScores(array, array);
//exit out
System.out.println("Press any key to exit...");
input.nextLine();
System.exit(0);
}
//validate user input
public static String validateUserInput ( String arrayInput){
//variable to itirate through the string
int counter = 0;
//variable to index
int arrayInputLength = arrayInput.length();
//assign scanner for user input
Scanner input = new Scanner(System.in);
//loop to check if blank
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
//loop to check if user inputs numbers mixed with letters, iterate using counter
while (arrayInputLength > counter){
if (!Character.isDigit(arrayInput.charAt(counter))){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
counter = 0;
}
else{
counter ++;
}
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
//loop to check while there is something inputted, make sure only between 0 and 100
while (arrayInputLength > 0 ){
int arrayInt = Integer.parseInt (arrayInput);
if (arrayInt > 0 && arrayInt <= 100){
return arrayInput;
}
else {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
while (arrayInputLength == 0 ){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
return arrayInput;
}
validateUserInput has too much responsibility (and duplicate code). It's trying to validate the user input and also get new input. But that new input might not be valid either (which is causing the error in your question).
Separate getting user input from validating the input. Consider changing
public static String validateUserInput ( String arrayInput)
to
public static boolean isValidInput(String arrayInput)
It only checks to see if the input is valid. It does not prompt the user for new input.
Then within the main for loop, keep prompting the user for input until it is valid.
for(...) {
....
while (!isValidInput(arrayInput)) {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
}
....
}
Related
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean isArrayInputStillGoing = true;
while (isArrayInputStillGoing){
System.out.println("Please enter the size of the array");
int sizeOfArray = input.nextInt();
if (sizeOfArray < 0){
System.err.println("Array cannot have a negative value try again");
continue;
}
int[] initialArray = new int[sizeOfArray];
System.out.println("Please enter the array elements");
for (int i=0;i<sizeOfArray;i++){
initialArray[i] = input.nextInt();
if (initialArray[i] <= 0 || initialArray[i] > 100){
System.out.println("Try again with a number between 1 and 100");
continue;
}
}
isArrayInputStillGoing = false;
renderArray(initialArray);
}
}
How can I make it so when a number less than 1 or more than 100 is inputed it requiers you to input that same number again. As is it just prints out the message and then prints the array with any inputed numbers even if they are wrong. Also it is saying that the continue is unneccesary since it is the end of the loop.
You are inserting the values in the array when the wrong number is sent to the array you continue in which the for loop increment the i counter then again new array is initialised just write i-- in the if block and you are all set also remove continue
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean isArrayInputStillGoing = true;
while (isArrayInputStillGoing){
System.out.println("Please enter the size of the array");
int sizeOfArray = input.nextInt();
if (sizeOfArray < 0){
System.err.println("Array cannot have a negative value try again");
continue;
}
int[] initialArray = new int[sizeOfArray];
System.out.println("Please enter the array elements");
for (int i=0;i<sizeOfArray;i++){
initialArray[i] = input.nextInt();
if (initialArray[i] <= 0 || initialArray[i] > 100){
System.out.println("Try again with a number between 1 and 100");
i--;
}
}
isArrayInputStillGoing = false;
}
}
Instead of assigning input.nextInt() to the array at position i in initialArray[i] = input.nextInt(); you could first assign it to some candidate that you are going to test. You can achieve this by e.g. replacing the for loop as follows:
System.out.println("Please enter the array elements");
int i = 0;
while (i < sizeOfArray) {
int candidate = input.nextInt();
if (candidate <= 0 || candidate > 100){
System.out.println("Try again with a number between 1 and 100");
} else {
initialArray[i] = candidate;
i++;
}
}
I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
I'm trying to make code that asks the user to enter 10 numbers and subtracts them all. This is what i have so far. I think i have the general layout all set but i dont know what to do with the rest
import java.util.Scanner;
public class subnumbs
{
int dial;
int[] num = new int [10];
Scanner scan = new Scanner(System.in);
public void go()
{
int q=0;
dial = 10;
while (q != 0)
{
System.out.println("type numb: ");
int newinput = scan.nextInt();
q+=newInteger;
dial = cdial + 1;
}
return q;
}
}
System.out.printIn("Enter Integer: ");
int newInteger = scan.nextLine();
While (newInteger >= 0){
System.out.println("Re-enter Integer (must be negative): ");
newInteger = scan.nextLine();
}
n+=newInteger;
Counter = counter - 1;
return n;
this is one way to ensure inly negative numbers, only count down and add it if it was negative ...
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0) {
n+=newInteger;
counter -= 1;
}
else {
System.out.println("must be negative integer, please try again: ")
{
}
In general, to ensure an input you have to evaluate it at the point where you are getting the input
//Input Number
System.out.print("Enter a number from 1-10: ");
words = input.next();
//Processing String
if(!words.equals(FLAG)){
while(!words.equals("1") && !words.equals("2") && !words.equals("3") &&
!words.equals("4") && !words.equals("5") && !words.equals("6") &&
!words.equals("7") && !words.equals("8") && !words.equals("9") &&
!words.equals("10")){
System.out.print("Please enter a number in integer form from 1-10: ");
words = input.next();
}
}
//Close Scanner
input.close();
//String to Integer
num = Integer.parseInt(words);
//Output Number
if(num >=1 || num <=10){
System.out.println("\nYour number is: " + num);
}
How could i change the while loop? What if the number range was from 1-100? IS there any way to shorten the processing string segment? The program needs to be able to handle string and integers.
Parse it to an Integer
int number = Integer.parseInt(words);
and loop :
while( !(number > 0 && number <= 10) ){ // loop the loop }
N.B: Because you will be using parseInt(), you will need to learn to use try-catch blocks. Do look it up.
You can also directly use nextInt() method of the Scanner class for an input of Integer data type.
So you can do,
num = input.nextInt();
and then directly,
//Output Number
if(num >=1 || num <=10){
System.out.println("\nYour number is: " + num);
}
Make a min int and a max int.
int min =1;
int max =10; // change to 100 for if you wanted it bigger
Then when you get their value simply parse it(Parse turns it into an Interger)
int value= Integer.parseInt(words);
The final while loop would look like this:
while( !(number > min && number <= max) ){
//Your code
}
The easiest way to 'shorten' it would be to parse it before the while loop. You should be throwing NumberFormatException and putting your code in a try/catch block if you're going to be parsing strings to ints.
public void f() throws NumberFormatException{
try{
// other code
num = Integer.parseInt(words);
while( !(num>0 && num<=10) ){
// magic
}
// other code
}catch(NumberFormatException e){
// handle it!
}
}
Use a do while loop so that you don't have to ask the user for input twice, just let the loop do the work for you.
int number;
final int MIN = 0;
final int MAX = 100;
do
{
System.out.print("Please enter a number in integer form from 1-10: ");
words = input.next();
number = Integer.parseInt(words);
}while(!(number > MIN && number <= MAX));
Parse the input into an Integer before check validation.
But do remember to handle exception properly.
int number;
while(true){
try{
number = Integer.parseInt(words);
if(number <= 10 && number >= 1) break;
else
System.out.print("Your number is out of range (1, 10):");
}catch(NumberFormatException e){
System.out.print("Please input valid number from 1 to 10:");
}
words = input.next();
}
System.out.println("Your number is " + number);