java loop array using do...while - java

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);

Related

range between the min and max value

Create a NumberInTheRange application that prompts the user for two numbers.
The first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. Be sure to include the min and max numbers in the prompt.
I wrote a code allowing the users to write the two min and max values. However, I am wondering what code should I write in order to fulfill the conditions above. I am thinking about using loops and it would be very helpful if you guys correct me and give some instructions on how to process these.
import java.util.Scanner;
public class NumberinTheRange {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type two numbers:");
int n1=scan.nextInt();
int n2=scan.nextInt();
}
}
Use a do...while loop.
int num;
do {
System.out.println("Enter a number between " + n1 + " and " + n2 + ":");
num = scan.nextInt();
} while(num < n1 || num > n2);
Now, you need to put a condition to loop-back if the input is not in the range. You can use a do-while loop for the same. You can do it with any other loop but using a do-while loop guarantees that its body will be executed at least once.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Type two numbers: ");
int min = scan.nextInt();
int max = scan.nextInt();
int n;
do {
System.out.print("Enter a number in the range of " + min + "-" + max + ": ");
n = scan.nextInt();
} while (n < min || n > max);
System.out.println("Your number is: " + n);
}
}
A sample run:
Type two numbers: 10 20
Enter a number in the range of 10-20: 34
Enter a number in the range of 10-20: 5
Enter a number in the range of 10-20: 15
Your number is: 15

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)

getting number from the same line

I was wondering how you can the scanner can pick up all the different numbers on the same line. my assignment has requires us to compute grade averages and he wants it to be like:
Enter the number of grades: 5
Enter 5 grades: 95.6 98.25 89.5 90.75 91.56
The average of the grades is 93.13
I think for the scanner to get those number it requires an array? but we haven't learned those. Any help would be awesome! So far I have:
// number of grades input
do {
System.out.println("Enter number of grades");
// read user input and assign it to variable
if (input.hasNextInt()) {
numGrade = input.nextInt();
// if user enters a negative grade will loop again
if (numGrade <= 0) {
System.out.println("Your number of grades needs to positive! Try again");
continue;
// if grade number > 0 set loop to false and continue
} else {
cont = false;
}
// if user does not enter a number will loop again
} else {
System.out.println("You did not enter a number! Try again");
// get the next input
input.next();
continue;
}
// only not loop when boolean is false
} while (cont);
// user input of grades
do {
// prompt user to enter the grades
System.out.println("Enter the " + numGrade + " grades");
// assign to input
if (input.hasNextDouble()) {
grades = input.nextDouble();
// check if a grade is a negative number
if (grades <= 0) {
// report error to user and loop
System.out.println("Your grades needs to positive! Try again");
continue;
// if user enter acceptable grades then break loop
} else {
cont2 = false;
}
// check if user entered a number
} else {
// if user did not enter number report error
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
// only not loop when boolean2 is false
} while (cont2);
// average calculation
average = grades / numGrade;
System.out.println(average);
}
I would suggest this
// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"}
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
//parse each value to double and adds it to total
total+=Double.parseDouble(grades[i]);
}
double average= total/grades.length;
I think in your assignment the separate spaces means that you should have each number stored in a specific location or variable.
For example:
Enter three number : 1 2 3
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
now Scanner will read by nextInt() method. if it read space then will finished saving value in that variable.
Another Example that read array elements:
Enter three number: 1 2 3
int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
myArray[i] = input.nextInt();
}
Note that the loop will run 3 times as the length of the array.
Also note in the code that input reference for Scanner class but I didn't declare it.

sentinel value and displaying my results

I've been trying to figure out my code for hours and I know this is probably something simple but I would really appreciate some help!
Here's my problem:
// Purpose: This program will prompt the user to enter a positive integer.
// The program will accept integers until the user enters a -1.
// Once the -1 is entered, the program will display the integers followed
// by their sum.
import java.util.Scanner;
public class InputSum
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// variable declaration
int inputNumber;
int stringNumber = 0;
int num = 0;
int sum = 0;
// prompt user to enter an integer
System.out.print("Enter a positive integer: ");
inputNumber = scan.nextInt();
// continue to have user enter integers until:
while (inputNumber >= 0)
{
sum += inputNumber;
stringNumber = inputNumber++;
System.out.print("\n Enter another positive integer (enter -1 to quit): ");
inputNumber = scan.nextInt();
// -1 is entered
if (inputNumber == -1)
{
break;
}
}
// display results
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
System.out.print("\n The sum of the intergers are: " + sum);
}
}
Right now my results are showing my sum correctly, but it's supposed to display the integers I enter in a line separated by commas. (EX: if the user enters 1, 1, 1 my results should be The integers you entered were: 1, 1, 1 The sum of the integers are: 3). And right now it's adding my integers entered to the sentinel value and displaying my results as: The integers you entered were: 1.
I'm really stuck on how to do this. Any suggestions? Thanks!
You must store the input each time.
Replace
stringNumber = inputNumber++;
by
stringNumber += inputNumber+", ";
This will store the inputs in inputNumber.
Change
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
into
System.out.print("\n The integers you entered were: " + stringNumber);
This will display all inputs entered.
You are only printing the last number you entered :
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
If you wish to print all the input numbers, you have to store them somewhere.
If you wish to store them in stringNumber, change its type to StringBuilder, and append each number to it.
StringBuilder stringNumber = new StringBuilder();
...
stringNumber.append(inputNumber);
stringNumber.append(", ");
...
System.out.print("\n The integers you entered were: " + stringNumber.toString());
You'll have to make a slight adjustment to this code, in order to avoid printing an extra "," after the last number.

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

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);
}
}

Categories

Resources