Having Trouble Making a for loop with a do-while loop - java

just started with Java and my assignment this week is to write a program that asks the user how many test scores they want to enter, which the user fills in and then the program asks them to enter test scores up until that counter is met, and display the average amongst the scores.I feel like i have the brunt of it but just need some more help its kind of in a dead loop and I'm stuck. I've moved my for loop around and it either puts my display text into a neverending loop or the program stalls after asking for number of scores to be entered (this is where it is now). Any help is appreciated:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int count = 0;
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
while (testScore <= 100)
{
// get the input from the user
System.out.print("Enter the number of scores to be entered: ");
for (scoreCount = 0; count <=100; scoreCount++)
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.println("Enter more test scores? ('y' to continue, 'n' to close): ");
choice = sc.next();
System.out.println();
}
}
}

Try something like this:
// put this above main() - this way you can use it without ever defining a `Scanner` object again
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// store number of scores to enter
int numScores = 0;
// input number of scores to enter
System.out.print("How many scores would you like to enter? ");
numScores = in.nextInt();
// store sum of scores
int scoreTotal = 0;
// input scores
for(int i = 0; i < numScores; i++)
scoreTotal += in.nextInt();
// print count, sum, and average of scores
System.out.printf("\nScore count: %d", numScores);
System.out.printf("\nScore total: %d", scoreTotal);
System.out.printf(\n Average score: %d", scoreTotal/numScores);
}
I think this should run, but it may have a bug or two. I do not have Java any more, but I will be able to help if it produces an error. Just place this in your class and see how it works. You shouldn't need to modify it at all.

it is not a good idea to have so many nested whiles, it is very inefficient.
it is a good idea to surround the code with try/catch blocks, I didn't put it in there since I'm not sure you have learnt it.
I think you should take user input as total amount of scores, instead of using 100 in the for loop.
anyway, this is what I would do, hope this code helps:
import java.util.Scanner;
public class test{
public static void main(String[] args){
int count = 0;//amount of scores entered by user
int total = 0;//total score added up
int current = 0;//current amount of scores entered
System.out.println("How many scores would you like to enter?");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
do{
System.out.println("current amount of scores entered is "+current+" please enter the next score");
total += sc.nextInt();
current ++;
}
while(current < count);
System.out.println("the average score of "+current+" entered scores is "+total/count);
}
}

Related

Getting information out of a whole array to a variable?

I'm new to Stack Overflow So please go easy on me :D
I'm having some problems solving this problem, because of my data is stored inside of an array I need a way to be able to put the same data inside of a variable because I need to do some operation to get the average score, the first thing that I try to do was making a variable and giving it the array as the value but it was not allowing me to do anything, I've spent quite a lot of times on it and I still cannot like understand how to fix it, so if you could please help me out with this problem.
So to summarise what I'm trying to do is get the number of students that I have stored in i and the percentage Of the students that should be in array[i], this is to obtain the average score for the number of students, so the Sum Of Percentages / number of Students * 100 = Average Percentage of Score.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("Hello MJ ");
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i++)
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
for (int i=0; i<studenti;i++)
{
System.out.println((array[i])+"%");
}
System.out.println("\nThe Average Score is: " + average + "%");
int average = (persentegesOfStudents)/students;6
}
Note that in order to get the average, you need to sum the scores, and then to divide by the number of students. Your second for loop looks like the right place to handle the sum, and in addition you need to declare the average variable before printing it. Here is some suggestion (see my comments):
public static void main(String args[]) {
System.out.println("Hello MJ ");
Scanner sc = new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i < studenti; i++) {
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i] = Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
int sum = 0; // Added a variable for sum
for (int i = 0; i < studenti; i++) {
System.out.println((array[i]) + "%");
sum += array[i]; // maintaining sum
}
int average = sum / array.length; // calculating the average
System.out.println("\nThe Average Score is: " + average + "%");
}
Note that you can make the average more accurate if you work with it as float and not integer.
Use a stream to process data. Convert your array to intSream
IntStream stream = Arrays.stream(arr);
intSream have many funtions like average, min , max, sum etc.

Assigning a double through scanner isn't reading the first input

I'm currently writing a program for a class. The goal is to be able to have the user enter an integer, and initialize an array with that entered size. Afterwards, the program prompts the user for inputs going to each of those array slots ( grades as seen below ). We're also supposed to utilize a while loop when an input isn't valid. My issue is that when asking for the first grade, it requires two number inputs to loop through.
import java.util.Scanner;
public class ForWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int arraySize;
System.out.print("Gpa Calculator");
System.out.print("\nEnter total classes: ");
arraySize = scanner.nextInt();
double[] grades = new double[arraySize];
for (int i = 0; i < arraySize; i++) {
System.out.println("Enter grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
}
}
}
This is currently what I have written, but in the console I would expect for an input of 2:
GPA Calculator
Enter grade for class 1: 90
Enter grade for class 2: 85
What needs to happen for it to progress is:
GPA Calculator
Enter a grade for class 1: 90
90
Enter a grade for class 2: 85
I've tried using scanner.hasNextLine() but not to much success, what am I missing? I also think my while loop condition isn't looping correctly, any input would be much appreciated!
You are currently checking if there is a double to read after you have read the double. This,
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
should be
while (!scanner.hasNextDouble()) {
scanner.nextLine(); // consume the thing that isn't a double
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
}
grades[i] = scanner.nextDouble();

java code not working as I am expecting

I am really struggling on getting my java code to work. I have coded a program which determines what grade each score will get once entered in by the user and also finds the largest and smallest score. The program successfully figures out which score belongs in which grade but once I implement the piece of code which tries to find the largest number out of the scores it doesn't seem to work and I'm not sure what it is!
here is the code...
import java.util.Scanner;
public class Grade
{
public static void main(String[] args)
{
int Agrade=0; //different variables used throughout the code
int Bgrade=0;
int Cgrade=0;
int Dgrade=0;
int Fgrade=0;
int count=0;
Scanner in = new Scanner(System.in); //name of Scanner
System.out.println("Please enter the exam grades one after the other ");
System.out.println("Please enter a negative number at the end of the grade list to control the flow and then press enter :");
int score = in.nextInt(); //stores numbers inputted
System.out.println("Please enter the grades again for the largest number: ");
double largest = in.nextDouble();
while (in.hasNextDouble()){
double input = in.nextDouble();
if (input > largest) {
largest = input;
}
}
while(score>0) //start while loop
{
count++;
if(score>=70 && score<=100)
Agrade++;
else if(score>=60 && score<=69)
Bgrade++;
else if(score>=50 && score<=59)
Cgrade++;
else if(score>=40 && score<=49)
Dgrade++;
else if(score>=0 && score<=39)
Fgrade++;
score = in.nextInt();
} //end while
System.out.println("Total number of grades :"+ count);
System.out.println("The largest number :"+ largest);
System.out.println("The number of As :"+ Agrade);
System.out.println("The number of Bs :"+ Bgrade);
System.out.println("The number of Cs :"+ Cgrade);
System.out.println("The number of Ds :"+ Dgrade);
System.out.println("The number of Fs :"+ Fgrade);
} // end main
} // end class
Thank you!
That's probably an exercise so will give just the idea.
Your while loop seems to be fine, just declare two variables before it.
one for holding the max grade initialized with lowest number and another for min grade with highest number.
score = in.nextInt(); do
if ( score > highest ) { highest = score;}
if ( score < lowest ) { lowest = score }
good luck.
The problem is likely that you are declaring the variable input every time the while loop runs. Instead, declare the variable like this:
double input;
and do it before the while loop. Then in the while loop replace that line with:
input = in.nextDouble();
If this isn't the problem, it might be how you've laid out the code. The second while loop, which begins with while (score>0) should be where you have the line int score = in.nextInt() Putting this after the first while loop means that it's executed after that while loop.
As a side note, common variables like Agrade should be written in camelCase, in which the first letter is lowercase and the letter of the next word is uppercase. This would make your variables
int aGrade = 0;
int bGrade = 0;
and so on. This is just proper form and shouldn't effect your program. Also, you should probably declare score and input at the top of your program since you use them in loops. This is also good form and organization. It would look like this:
int score;
double input;
Check comments on code to understanding.
MainClass:
import java.util.Scanner;
public class Grade
{
public static void main ( String [ ] args )
{
/**
* This gradesCount represent the A,B,C,D,E,F counts
*/
int[] gradesCount = {0,0,0,0,0,0};
double inputScore = 0;
double bestScore = 0;
int total = 0;
#SuppressWarnings ( "resource" )
Scanner in = new Scanner(System.in);
System.out.println ( "If you want to end, enter a negative number" );
System.out.print("Enter score: ");
do
{
inputScore = in.nextDouble ( );
//validation for the first iteration
if(inputScore < 0 || inputScore > 100) break;
System.out.print("Enter score: ");
//Add to corresponding grade count
if(inputScore>=70 && inputScore<=100) gradesCount[0]++;
if(inputScore>=60 && inputScore<=69) gradesCount[1]++;
if(inputScore>=50 && inputScore<=59) gradesCount[2]++;
if(inputScore>=40 && inputScore<=49) gradesCount[3]++;
if(inputScore>=0 && inputScore<=39) gradesCount[4]++;
//Add one to total
total++;
//check best score
if(inputScore > bestScore) bestScore = inputScore;
}//This pattern check if its number between 0-100
while ( in.hasNext ( "[0-9][0-9]?|100" ) );
System.out.println ( "Negative number or not valid input. Exited." );
System.out.println("Total number of grades :"+ total);
System.out.println("The best score :"+ bestScore);
System.out.println("The number of As :"+ gradesCount[0]);
System.out.println("The number of Bs :"+ gradesCount[1]);
System.out.println("The number of Cs :"+ gradesCount[2]);
System.out.println("The number of Ds :"+ gradesCount[3]);
System.out.println("The number of Fs :"+ gradesCount[4]);
}
}
Input/Output:
If you want to end, enter a negative number
Enter score: 5
Enter score: 10
Enter score: 15
Enter score: 20
Enter score: 33
Enter score: 99
Enter score: 100
Enter score: 44
Enter score: -3
Negative number or not valid input. Exited.
Total number of grades :8
The best score :100.0
The number of As :2
The number of Bs :0
The number of Cs :0
The number of Ds :1
The number of Fs :5
Documentation:
Scanner
The while and do-while statements (used for iteration)
Pattern (used in do-while)

java loop array using do...while

This program should take a user defined number, create an array of that size and let the user input the elements - which are grades - using a do..while loop. The program then needs to display all grades entered from lowest to highest, accumulate the grades, and find the average.
My output isn't displaying the entered grades correctly (if I enter 10,20,30, it displays 00,10,20) and I can't figure out what I'm doing wrong. Any help, please?
import java.util.Arrays;
import java.util.Scanner;
public class LoopArray
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
int count = 0;
double totalAverage = 0;
double gradesTotal = 0;
System.out.println("Please input the number of grades you would like to submit for an average: ");
int numberOfGrades = keyboard.nextInt();
int[] studentScores = new int[numberOfGrades];
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Arrays.sort(studentScores);
for(count=0; count < studentScores.length; count++)
{
System.out.println("Grades entered were: " + count + studentScores[count]);
}
totalAverage = gradesTotal / numberOfGrades;
System.out.println("The total of all grades entered is: " + gradesTotal);
System.out.println("The average of grades entered is: " + totalAverage);
}
}
Result
Grades entered were: 00
Grades entered were: 10
Grades entered were: 20
is generated with
System.out.println("Grades entered were: " + count + studentScores[count]);
So last number in each line is pair representing count + studentScores[count]. This means that:
00 -> at position 0 array studentScores stores 0.
10 -> at position 1 array studentScores stores 0
20 -> at position 2 array studentScores stores 0
Which means you didn't fill your studentScores array with values from user.
You are not putting any value inside the array. You need to add this to your do part of the loop studentScores[count] = inputGrade;
Now your do while loop should look like this:
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count] = inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Also, inside your last for-loop, you are printing extra info. Just remove that count from System.out.println
System.out.println("Grades entered were: " + studentScores[count]);
Anything you don't understand let me know thanks
Because count start from 0. You should check it.
you forgot to populate the array using the gardes entered
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count]=inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);

Only allowing numbers to be taken from user input in java

I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);

Categories

Resources