Setting a while loop that validates multiple input? - java

I need help validating input. I have a program that works with student grades based off user input. if someone enters grades below 0 or over 100 I want this loop to restart. Here is what I have so far:
double scores[] = new double[size];
for (int i = 0;i<= scores.length-1;i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
}
System.out.println("Here are your scores: " + Arrays.toString(scores));
I'm confused on how to implement invalid checker. I know it has something to do with a while loop. such as while a value is 0, and if someone enters invalid answer it will change from 0. But not sure how exactly I should do this, or if theres a better way
Any help appreciated. thanks

You can make use of a nested while loop and conditional statement for this:
for (int i = 0;i< scores.length;i++){
while(true){
System.out.print("\n\nScore number " + (i+1) + ": ");
int score = sc.nextInt();
if(score >= 0 && score <=100){
scores[i] = score;
break;
}else{
System.out.println("Error: score entered is outside allowable range");
System.out.println("Please try again");
continue;
}
}
}

You can simply ask the user to re-enter the value of the score which has been entered wrong.
double scores[] = new double[size];
for (int i = 0; i<= scores.length-1; i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
if(scores[i] < 0 || scores[i] > 100) {
i -= 1;
continue;
}
}

I'm confused on how to implement invalid checker. I know it has something to do with a while loop.
do-while loop is preferred in input validation because it allows input to be received first, then check if it passes the requirement. If input is invalid, repeat.
for(int i=0; i<scores.length; i++){
do{
System.out.print("\n\nScore number " + (i+1) + ": ");
input = sc.nextInt();
}while(input < 0 || input > 100);
scores[i] = input;
}
The for-loop and do-while loop serve different purpose. Hence, do not be confused by the
- for-loop which is only responsible to receive multiple inputs for the array and the
- while loop which is only responsible for validating every single input.

Related

how not to allow a negative number to be entered in for

I have tried Math.abs and if statement and nothing works. I am a bit confused. How can I not accept negative numbers with for loop in Java , the user can not enter negative numbers as defense programming? Take the following piece of code :
for(int i=0; i<arr.length; i++) {
System.out.print("Νο. " + (i + 1) + ": ");
arr[i] = input.nextDouble();
}
Wrap the reading of the value in a loop. Do not exit the loop until the the user enters a non-negative value. For example..
for (int i=0; i<arr.length; i++) {
while (true) {
System.out.print("Νο. " + (i + 1) + ": ");
arr[i] = input.nextDouble();
if (arr[i] >= 0) {
break;
}
System.out.println("Value cannot be negative");
}
}
I suppose you are pretty new to Java. Welcome to Java's magical world :)
Depending on what your code looks like, a more "professional" way is to throw an exception: You may Google a little bit and try to customize your code and how it will react to the exception.
On the other hand, it seems like a simple project, so something like
Double a = input.nextDouble();
if(a > 0){
System.out.println("No negative values allowed");
}else{
arr[i] = a;
}
could be enough

Arithmetic mean in java

Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);

how do i get my code to calculate the number of place correct place values?

I am not really good at coding and I've been confused in this step where I don't know to make my code read the correct number of place values.
For example I run my code and it generates 5 random numbers then I input 5 random numbers the output of this would be "They share 0 numbers in the right place value.
For example,in order for me to get what I want, I get 5 random generated numbers which are 54123, I input 00123 it would say they hold 3 numbers in the right place value.
//this is what I think something needs to be edited
//This is my whole code on a google doc: https://docs.google.com/document/d/1ug1rRNwgZwBAf9kvaeAEFoo81r_W9Br6rRX4xc0fFUk/edit?usp=sharing
//I didn't enter my whole code on this post because I think it is to long and the only part I want is where it can calculate how many numbers in the right place value
System.out.println(s);
String f = scan.next();
for(int p=0; p<s.length(); p++) {
for(int z=0;z<f.length();z++){
if (s.substring(p,p+1).equals(f.substring(z,z+1))){
n++;
} }}
int rt= 0;
for(int p=0; p<s.length(); p++) {
for(int z=0;z<f.length();z++){
// this where i count the numbers in the right place
rt=99;
} }
System.out.println(" They share " + rt + " numbers in the right place value");
System.out.println(" They share " + n + " numbers in common");
System.out.println("guess number 1");
if(n ==5){
System.out.println(" Congratulations you win! ");
System.exit(0);
}
String generatedNums = "54123";
String nums = "00123";
int length = generatedNums.length() <= nums.length() ? generatedNums.length() : nums.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (generatedNums.charAt(i) == nums.charAt(i)) {
count++;
}
}
System.out.println(count);

How to close a while loop

I thought my code was correct but when I ran it, my output statements at the bottom wouldnt produce. I'm asking the keyboard to enter any number and then to end by entering -1. My while loop includes adding numbers, creating a sum, as well as giving the amount of even numbers. When I test my code I've been entering just 1,2,3,4 hoping to produce 4 total numbers. 2 even, and a sum of 10. Why isnt' my code getting to the print statements?
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a number. Enter -1 to stop program.");
int num = sc.nextInt();
int counter = 0;
int even = 0;
int sum = 0;
while (num != -1)
{
counter += 1;
sum += num;
if (num%2 == 0)
{
even +=1;
}
}
System.out.println("You have entered "+ counter + "number(s)");
System.out.println("You have entered "+ even + "even numbers");
System.out.println("The sum for the numbers you entered is "+ sum);
}
You never get the input again so the loop runs infinitely. You need to get the value again.
while (num != -1)
{
...
num = sc.nextInt();
}
num gets set before you enter the loop.
So, when does the num change inside the while loop? It doesn't. That's why your code won't exit the loop.
I suggest moving the
num = sc.nextInt();
inside the loop.

Need assistance with Min and Max function?

I have an application a number guess game, users have to guess a number between 0 and 100, when they guess right the program asks them if they would like to play again when their done play I display the least number of guesses in a game and the greatest number of guess in a game. Right now all i get is the sum of all their guesses in the when using the "Math.min(,)"?
How do I get the minimum function to work??? the function code is in further below.
leastNumGuesses = Math.min(leastNumGuesses,guesses);
double rightNum = Math.random() *100;
int randomNum = (int) rightNum; //convert the random number to int
int tries = 0; //single game gussess output
int numberOfGames = 0;
int allTries = 0; //accumalates all tries(sum of all tries)
int guesses = 0; // guesses of all games combined
int gameGuesses = 0;
int leastNumGuesses = 100;
int mostNumGuesses = 0;
while (choice.equalsIgnoreCase("y"))
{
System.out.println();
int guess = getIntWithinRange(sc,"Enter the Number: ", 0, 100);
tries++;
guesses++;
gameGuesses++;
if (guess == randomNum)
{
numberOfGames++;
System.out.println("You got it in " + tries + " tries.");
leastNumGuesses = Math.min(leastNumGuesses,gameGuesses);
if (tries <=3)
System.out.println("Great work! You are a mathematical wizard.");
else if (tries > 3 && tries <= 7)
System.out.println("Not too bad! You've got some potential.");
else if (tries > 7)
System.out.println("What took you so long? Maybe you should take some lessons.");
System.out.println();
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
{
System.out.println("Error! entry must be \"y\" or \"n\".");
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
}
if (choice.equalsIgnoreCase("y"))
{ // reset the random number & tries
rightNum = Math.random() *100;
randomNum = (int) rightNum;
tries=0;
gameGuesses++;
}
else if (choice.equalsIgnoreCase("n"))
{
allTries += guesses;
int averageNumGuess = allTries / numberOfGames;
System.out.println("Bye - Come back again");
System.out.println("Number of Games Played: " + numberOfGames);
System.out.println("Average Number of Guesses: " + averageNumGuess);
System.out.println("Least Amount of Guesses In a Single Game: " + leastNumGuesses);
}
}
It seems that you're changing what you want guesses to stand for in the middle of the program.
Remember that guesses is the total number of guesses over all games played, and that leastNumGuesses is initially set to 100. In most cases, you will find that guesses < leastNumGuesses, and thus the Math.min(guesses, leastNumGuesses) function will return guesses.
To fix: use variable other than guesses, for example, gameGuesses to keep track of how many guesses were made in a game. Then, Math.min(,) will behave as you expect.

Categories