Java While loop skipping lines, doing them every 2 cycles instead - java

I'm writing a program for homework that is supposed to read in an unspecified number of 0-100 scores (maximum of 100 scores) and stop after -1 or any negative number is entered.
I've put this into a Do While loop that is set to terminate when -1 is pulled in through Scanner. The loop has a counter that keeps track of how many times the loop has been gone through, an adder that adds all the input lines together to later compute an average, and a means to send the input value to an array after it has checked to see if the number is -1.
Instead of doing this, the loop only increments the counter every 2 loops and -1 will only terminate the loop on an even cycle number, other wise it will wait until the next cycle to terminate. This completely baffles me, I have no idea why it's doing this. Could someone point out the error? Thanks in advance! This is all I have so far.
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while ( CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}

CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
You are calling twice In.nextInt(), i.e., you are reading two lines in each loop iteration.

CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;
Use this instead.

Related

Array keeps counting 0 as a number when I didn'

I'm trying to make a game show program where I enter the number of contestants, how fast they hit the buzzer, the fastest and slowest times for hitting the buzzer, and the number of people that hit the buzzer faster than average.
Everything goes well with my program when I have 5 contestants. But if I enter 4 contestants or anything else less than 5, it messes up some things. When I have 4 contestants, my fastest time is 0, even when I'm not putting in a 0 as a time, and the number of contestants that hit the buzzer faster than average is also messed up, having one extra than it should, because it's putting in a 0.
How do I stop this program from adding in a 0 when I don't have 5 contestants?
import java.util.Scanner;
public class FastestFingers {
public static void main(String[] args) {
//declare varialbes
int contestants;
int [] milisecs = new int [6];
int fastest, slowest, i;
int faster = 0;
double average;
Scanner scanInt = new Scanner (System.in);
//make user enter number of contestants
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
//make user enter times
for(i=1;i<=contestants;i++)
{
System.out.println ("Time (ms): ");
milisecs[i] = scanInt.nextInt();
}
//calculate fastest time
fastest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] < fastest)
{
fastest = milisecs[i];
}
}
System.out.println ("Fastest: " + fastest);
//calculate slowest time
slowest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] > slowest)
{
slowest = milisecs[i];
}
}
System.out.println ("Slowest: " + slowest);
//tell program how to find average
int total = 0;
for(i=1;i<milisecs.length;i++)
{
total = total + milisecs[i];
}
average = total/contestants;
//find numbers faster than the average
int count = 0;
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i]<average)
{
count++;
}
}
System.out.println ("Faster than average: " + count);
}
}
You create an int[] of fixed size 6. Then you compare the last 5 values to find the lowest. All int values are default 0. If you only set 4 values to anything larger than 0 the fifth value will always be 0 and therefore your lowest value.
You can fix this problem by setting the size of your array to the number of contestants.
Also remember that arrays start counting at 0 not at 1. Your loops should therefore be:
for(i=0;i<milisecs.length;i++), etc.
The problem is that you initialize the array to have six elements.
int [] milisecs = new int [6];
By default all of these values will be zero. Then in your loop you only initialize four of them, meaning that two will still be zero. Change your code to:
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
int [] milisecs = new int [contestants];
This will ensure that you will only have as many time slots as you have contestants.
Also array indexes start at zero, so you should change
fastest = milisecs[1];
to
fastest = milisecs[0];
And in your loops, start your variable at 0 instead of 1.
Array Index should start with 0. Please be careful with this. You code reads input and assigns to the milisecs starting from index 1.

Sequence of Integers that Returns Average at the End

Hey guys I need help with this assignment. When I run what I have it just loops forever, help would be much appreciated. Here's what my assignment is:
Write a program segment on the following page which reads a sequence of integers from the keyboard until 0 (zero) is entered. As it is entered print each integer (except for the 0 that stops the program) and at the average of the integers entered.
Each non-zero integer is printed on a separate line.
this continues until a zero is read, at which point the segment stops.
Here's what I have so far:
import java.util.Scanner;
public class List {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int boom = 0;
int sum = 0;
double average = 0;
int count = 0;
System.out.println("Enter a nonzero integer, please!");
boom = keyboard.nextInt();
while (boom != 0) {
sum += boom;
count++;
average = ((double) sum) / count;
System.out.println("The average is " + average);
}
}
}
You read the keyboard input only once. That's what you should do:
while (boom=keyboard.nextInt() != 0) {
sum += boom;
count++;
average = ((double)sum) / count;
System.out.println ("The average is " + average);
}
It will loop forever if you enter a non-zero integer at the boom=keyboard.nextInt() stage. The reason why is that boom never changes in your while block and the condition for stopping is that boom does not equal zero.
You'll need to set boom to a non-zero value outside of the loop and move your assignment to boom of the int from the keyboard inside the loop.

Sorting evens and odds between the range of two integers using while loops?

NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?

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.

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.

Categories