Having problems utilizing Arrays and for loops in a Java assignment - java

The program asks to "write a Java program that will first ask the user how many grades they want to enter. Then use a do..while loop to populate an array of that size with grades entered by the user. Then sort the array. In a for loop read through that array, display the grades and total the grades. After the loop, calculate the average of those grades and display that average."
The output is the issue. No matter what I do with the code, it will only output two of the inputs I have typed. If I chose to enter 4,5, or 10 grades. It will only show the lowest two. Although the total and the averages are correct. What is it that I am missing here?
Here is what I have written:
import java.util.Scanner;
import java.util.Arrays;
public class TapCoGradeArray
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int count;
double inputGrade = 0;
double gradeTotal = 0;
double[] individualGrade;
System.out.println("Enter the number of students that are being graded.");
int numberOfGrades = keyboard.nextInt();
individualGrade = new double[numberOfGrades];
count = 0;
do
{
System.out.println("Enter the grade (from 0-100) for each student below.");
inputGrade = keyboard.nextDouble();
individualGrade[count] = inputGrade;
count++;
gradeTotal+= inputGrade;
} while(count < numberOfGrades);
Arrays.sort(individualGrade);
for(count = 0; count == individualGrade.length; count++);
{
// This next line is using gradeTotal as an array. However, there is no array by that name.
// Check which array this should be.
System.out.println("The grades entered are the following: \n" + inputGrade + "\n" + individualGrade[count]);
}
double gradeAverage = gradeTotal / numberOfGrades;
System.out.println("The total of the grades is " + gradeTotal);
System.out.println("The average of the grades entered is " + gradeAverage);
}
}

Two main problems
for(count = 0; count == individualGrade.length; count++);
this should not have a seimcolon and looping until this values is reached is correct.
for(count = 0; count < individualGrade.length; count++)
{
System.out.println("The grades entered are the following: \n" +
inputGrade + "\n" + individualGrade[count]);
}

Related

Is there a way to have a System.out.print print something different once in a loop?

I'm very new to coding, and one of my projects was to create a program that uses a while loop to ask a user for test grades and find the average. The problem I have is that when it asks for the first grade, my instructor wants it to also print out "Enter -1 when you're finished" along with the first grade only. He wants the results to look something like this.
Test grade1? (Enter -1 when you are finished): random grade
Test grade2? random grade
Test Grade3? random grade
The average of your test grades is: average of all grades
Currently, I have the first grade as a separate line of code that asks the user and it is not in the loop. Is there any way to combine it into the loop and still have it to ask "Enter -1 when you're finished" but for only the first test grade?
P.s Sorry if my code is very messy I'm still not very good at it.
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Test grade 1? (Enter -1 when you're finished): ");
int grade1 = scan.nextInt();
int i = 2;
int testCounter = 1;
int sum = 0;
boolean flag = true;
while(flag) {
System.out.print("Test grade " + i + "? ");
int grades = scan.nextInt();
if (grades == -1){
flag = false;
break;
}
sum = grade1 + grades;
grade1 = sum;
i++;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double)sum/testCounter);
}
}
You can just check with an if statement whether it's the first test and display the additional message if that's the case.
Also you can get rid of the i variable and use testCounter in it's place. You also don't need the flag, just using break is enough.
At the end of the loop the testCounter will be off by one so you have to decrement by one when calculating the average ((testCounter - 1)).
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCounter = 1;
int sum = 0;
while (true) {
System.out.print("Test grade " + testCounter + "? ");
if (testCounter == 1)
System.out.print("(Enter -1 when you're finished): ");
int grade = scan.nextInt();
if (grade == -1) {
break;
}
sum += grade;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double) sum / (testCounter - 1));
}
}

TestScoreStatistics While Loop assistance

We are supposed to create a loop that repeats for the number of times needed by the student. I am completely lost when it comes to setting up a loop that doesn't run on a predetermined count in the code.
We have to create the loop. I dont really even know where to start since there is nothing in the book that I can see that address that style of condition yet.
Any help is appreciated to get me going in the right direction.
import java.util.*;
public class TestScoreStatistics
{
public static void main (String args[])
{
int score;
int total = 0;
int count = 0;
int highest;
int lowest;
final int QUIT = 999;
final int MIN = 0;
final int MAX = 100;
Scanner input = new Scanner(System.in);
System.out.print("How many scores would you like to enter >> ");
enterCount = input.nextInt();
System.out.print("Enter a score >> ");
score = input.nextInt();
//Create a while statement that will loop for the amount entered
while( count != QUIT )
{
}
System.out.print("Enter another score >> ");
score = input.nextInt();
}
System.out.println(count + " scores were entered");
System.out.println("Highest was " + highest);
System.out.println("Lowest was " + lowest);
System.out.println("Average was " + (total * 1.0 / count));
}
}
So. It seems that you want to request entering scores until the user entered as many scores as defined in enterCount:
List<Integer> scores = new ArrayList<Integer>();
while( count < enterCount ) {
System.out.print("Enter another score >> ");
score = input.nextInt();
scores.add(score);
count++;
}
You probably have to define some kind of List where you put the scores in.

Java average program with any number of inputs

What I'm trying to make is an averaging program that takes any number of inputs. So far I need to have the user specify how many numbers they want to average, and if they don't give that many numbers the program crashes. Is there any way that I could just have them put as many numbers as they want and afterwards the array length is set?
Here is the code I am using right now:
import java.util.*;
public class Average_any
{
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("How many numbers do you want to enter?");
final int ARRAY_LENGTH = scan.nextInt();
System.out.println ("Please type the numbers you want to find the average of, "
+ "and then type \"Done\".");
System.out.println ("Warning: Only type the exact amount of numbers that you specified.");
// If user doesn't enter same number, results in crash
double[] numbers = new double [ARRAY_LENGTH];
do {
for (int i = 0; i < numbers.length; i++) {
while (!scan.hasNextInt()) {
System.out.println("That's not a number!");
scan.next(); //Need this to enter another input
}
numbers[i] = scan.nextInt();
}
} while (!scan.hasNext("Done"));
double total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
double average = total/ARRAY_LENGTH;
System.out.println ("Your average is: " + average);
}
}
(Just in case anyone is wondering, no this is not a school assignment, I was just wondering because we did a simpler version in school)
Take the array out of the equation altogether
Scanner scan = new Scanner (System.in);
double total = 0;
int count = 0;
while (scan.hasNextDouble()) {
total += scan.nextDouble();
count ++;
}
double average = total / count;

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

populating the array with the user input

i apologize i know this looks simple but i'm kinda new to coding. the goal of the program is to take inputs from the user starting at index 0 and then save the inputs into the array. i'm probably close to solving this but i need some help.
here is the code:
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[numberOfGrades] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
Your logic is a bit off. numberOfGrades is the.. well.. number of grades. And when you do this: grades[numberOfGrades] = input.nextInt(); then you put the user's input in the grades array in location numberOfGrades, which you don't want.
What you do want is:
do {
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
This way, the array in location counter is accessed, and the user's input is placed inside it in the correct location.
Also, to calculate the average of the grades, like you are trying to do in the end of your program, you should do:
double sum = 0;
for (int grade : grades)
sum += grade;
And then your average will be:
average = 1.0d * sum / grades.length;
You can just as well put this summing logic inside your do-while loop and avoid the extra loop I introduced.
this instruction
grades[numberOfGrades] = input.nextInt();
must be replaced by
grades[counter] = input.nextInt();
try this ...
The thing that you were doing wrong is in the do while loop you were inserting value in the same array index grades[numberOfGrades] = input.nextInt(); should be replaced by grades[counter] = input.nextInt();
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
You can try like this
public class ArrayTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter number of elements");
int n=input.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=input.nextInt();
}
for(int i: arr){ //for printing array
System.out.println(i);
}
}

Categories