Run loop an extra time if one of the inputs is bad - java

I have a for-loop which asks for scores between 0 and 10. It asks a certain amount depending on the number of judges.
Here's the code:
System.out.println("Number of judges: ");
int numOfJudges = IO.readInt();
int sum = 0;
for (int i=0; i<numOfJudges; i++) {
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
} else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
System.out.println(sum);
I want to make is so if a number is entered that's not between 0 and 10, it won't count that as one of the conditions as i < numOfJudges.
For example if I have 3 judges and I enter 2 wrong inputs, it will still only run the loop 3 times (and only take the good input into account) while I really want it to run 5 times to make up for the two incorrect inputs.

Increment numOfJudges in case of ELSE condition so that your FOR loop would run until you have desired number of correct inputs.
This is shortest and cleanest solution.
else {
System.out.println("Incorrect number, must be between 0 and 10.");
numOfJudges++;
}

You can use a while loop inside of the for-loop, instead of adjusting the for-loop:
for (int i=0; i<numOfJudges; i++) {
while(true){
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
break; //jump out of while-loop
}else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
}
System.out.println(sum);

Related

How to swap numbers in while loop java

import java.util.Scanner;
public class Swap {
// if the number is less than 10, swap the last two numbers and print them.
public static void main(String[] args) {
// User to enter a number between 1 and 10, but not zero.
Scanner number = new Scanner(System. in );
System.out.println("Enter a Integer(whole number) between 1 and 10. : ");
int userNum = number.nextInt();
while (userNum > 10 || userNum < 0) {
System.out.println("Try again: ");
userNum = number.nextInt();
}
System.out.println("Your number loop");
while (userNum <= 10) {
System.out.println(userNum);
userNum++;
}
System.out.println("Guess the two swap numbers:");
}
}
How do I swap the last two numbers? I am a beginner learning java and OOP. I have created this program where the user has to enter a number between 1 and 10. If the user enters a number below 1 and above 10, the user gets prompted to try again. Then it prints the list of numbers based off the users input. e.g. if the user enters 8, its prints the loop 8,9 and 10. I have having trouble, I understand how to swap two variable, not inside a loop. Thank you and much appreciated for your help.
Let's assume that the maximum number is a parameter N, so that you could swap any last two numbers and place N before N - 1
private static final int N = 10;
There are several ways to do this using different Java operators:
if, to update delta parameter
while (userNum <= N) {
int delta = 0;
if (userNum >= N - 1) {
delta = userNum == N - 1 ? 1 : -1;
}
System.out.println(userNum + delta);
userNum++;
}
or simply skip N - 1 and print it after the loop:
while (userNum <= N) {
if (userNum != N - 1) {
System.out.println(userNum);
}
userNum++;
}
System.out.println(N - 1);
switch
while (userNum <= N) {
int printNum = userNum++;
switch(printNum) {
case N:
printNum--; break;
case N - 1:
printNum++; break;
default:
break;
}
System.out.println(printNum);
}
two consequent loops (the second going backwards):
while (userNum < N - 1) {
System.out.println(userNum++);
}
userNum++;
while (userNum >= N - 1) {
System.out.println(userNum--);
}
another way this can be solved is by creating a loop(for or while) and taking the two numbers you can use the math functions- Math.max(a,b) || Math.min(a,b) to find the biggest and smallest numbers. Afterwards you can create more variables- c&d to save the two numbers.
goodluck
a=max
b=min
then
c=a
d=b;
then a=d and b=c.

Not including a number as a variable from user input and having it increment another variable?

My programs asks the user to input integers (on a loop) until they input -99; which will then display the highest and lowest numbers of the input integers. I have a variable called count, that increments every time the user puts in a new integer, to keep track of the number of integers inputted by the user. How can I have -99 not included as one of the integers and not incrementing count?
Code:
//variables
int num = 0, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
low = num;
high = num;
//loop
while(num != -99){
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++;
if (num == -99 && count == 0)
{
count--;
System.out.println("You did not enter a number");
} //outer if end
else {
//higher or lower
if(count > 0 && num > high)
{
high = num;
} //inner else end
else if(count > 0 && num < low)
{
low = num;
} //inner else if end
else
{
} //inner else end
} //outer else end
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You approach is good, but you missed some points,
your condition to find max or min is also wrong because you have to write them separately.
User Entered any value or not, you have to decide this outside the loop.
You have to initialize high and low with first input.
I am trying to make some correction in your program, just changing the required part. Hope it will help you.
//variables
int num = 0, count = 0, high =0 , low = 0;
Scanner userInput = new Scanner(System.in);
//loop
while(true){
//Using infinite loop, we will break this as per condition.
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
if(num == -99)
{
break;
}
count++;
if(count == 1)
{//initialize high and low by first number then update
high = num;
low = num;
}
//to check highest
if(num > high)
{
high = num;
}
//to check smallest
if(num < low)
{
low = num;
}
}
if (count == 0)
{//Here we check that if user enter any number or directly entered -99
System.out.println("You did not enter a number");
}
else
{
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
}
I would recommended the following solution :
First of all, get a number from the user before the loop.
Then check if the number is -99 or not.
You know what to do if it is.
If not, start a do-while loop and do the following :
Increment the count.
Update your low and high.
And the last statement of the loop body will get another number from the user.
The while condition after the loop body will check that the latest number entered is not -99.

Which part of my program is in the wrong loop? JAVA

The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)

Using a while loop to compare to a value in a array

I need the program to run in a loop until 0 is entered. My code will end with 0 entered but when attempting to run the program with numbers entered it still ends the program. instead of running the numbers entered. The while loop is to keep the program running unless a 0 is entered.
import java.util.Scanner;
public class CountCompare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100 (0 to end, 0 < to exit): ");
int[] counts = new int[100];
// Count occurrence of numbers
count(counts);
while(counts[0] > 0){
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.println((i + 1) + " occurs " + counts[i] +
" time" + (counts[i] > 1 ? "s" : ""));
}
System.out.print("Enter the integers between 1 and 100 : ");
// Count occurrence of numbers
count(counts);
}
System.out.print("\nEnd of run");
}
/** Method count reads integers between 1 and 100
* and counts the occurrences of each */
public static void count(int[] counts){
Scanner input = new Scanner(System.in);
int num; // holds user input
do {
num = input.nextInt();
if (num >= 1 && num <= 100)
counts[num - 1]++;
} while (num != 0);
}
}
I have posted the entire program.
output looks like this
Enter the integers between 1 and 100 (0 to end, <0 to exit):
23 23 4 5 6 7 8
0
4 occurs 1 time
5 occurs 1 time
6 occurs 1 time
7 occurs 1 time
8 occurs 1 time
23 occurs 2 times
Enter the integers between 1 and 100:
Your program still ends because:
int[] counts = new int[100];
You have defined the limit of the counts here. This means your loop will run
for (int i = 0; i < counts.length; i++)// counts.length=100;
So as far as you code suggest you want to end the user input when user input 0. So you might do this:
int x=1;
int y;
Scanner sc= new Scanner(System.in);
while(x!=0){
System.out.println("Enter your values");
y=sc.nextInt();
if(y==0){
x=0;
}
else{
System.out.println("You entered "+y);
}
int count=new Scanner(System.in).nextInt();
int myarray[]=new int[count];
for(int tmp=0; tmp<count;)
myarray[tmp]=++tmp;
while(count != 0){
for(int inc=1; inc<=count; inc++){
System.out.println(inc + "times occur");
}
System.out.println("Enter 0 to exit");
count=new Scanner(System.in).nextInt();
}
You should take a look at the line
while(counts[0] > 0) {
and try to figure out what is the purpose of this while loop in the main method.

Golf score program?

So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.

Categories

Resources