Java program how to read multiple Doubles in one line? - java

Alright,so I've got this assignment that requires me to have a method with a variable number of inputs as well as a string input. The inputs all have to be on one line in the scanner, and the method has to return the number of values entered,the average value,the max value,the min value,and the string that was entered.
This is an example of that the terminal window should look like.
Please enter the name of the course: CourseNameHere
Please enter the scores for CSC 201 on a single line and type a -1 at the end
71 02 81 44 84 17 38 11 20 05 93 -1
The course name : CourseNameHere
Number of Scores : 11
The Average Score : 42.37
The Minimum Score : 02
The Maximum Score : 93
The Average score has to be rounded to 2 decimal places(which I think I can handle) The only problem for me is getting the variable number of inputs to be scanned on a single line,and how to have the program count the number of inputs if I'm not hitting enter between the inputs. This is what I have so far.but I have no idea where to go from here. I can get it to ask for sequential values,but they aren't all on the same line
I would also like to know what i would put as my return in the method? im new to java please help
this is my program that calculates the code without reading it with one line but reading them in separate lines all i need is how to read them in the same line:
System.out.println("Please enter the number of courses that you would like to\n" + "calculate the Average Score, the Minimum Score and\n" +"the Maximum Score: "); // prompt the user to enter the number of courses for which the average, min and max neeed to be calculated.
//create a scanner object to read from the keyboard
Scanner input = new Scanner(System.in); //declares a new scanner called input to take input from keyboard
int count = input.nextInt(); // read the user input and store it in the count variable
input.nextLine(); //read the end of the line and throw it away
for (int i = 0; i < count; i++)
{
System.out.println("Please enter the name of the course: "); // prompt user to enter course name
String courseName = input.nextLine(); // stores user input from keyboard into variable courseName
System.out.print("Please enter a score for "+ courseName + " or type -1 to indicate\n" + "that there is no more score for this course: "); // prompt the user to enter a grade in the class
double score = input.nextDouble(); // stores user input for score into variable double
int numberOfScores = 0; // declare integer variable called numberofscored and set value to 0
double total = 0; // declare a double variable called total and set value to 0
double min = 100; // declare double variable called min and set value to 100
double max = 0 ; // declare double called max and set value to 0
while (score!=-1) // start while loop for when score does not equal -1
{
if ( score < min) // start of if statement
{ min = score;
} //end of if //start of if statement
if ( score > max)
{ max = score;
} // end of if statement
total = total + score; // sets the value of variable total equal to itself + score
numberOfScores++; // adds 1 to the variable numberofscores
System.out.print("Please enter a score for "+ courseName + " or type -1 to indicate\n" + "that there is no more score for this course: "); // prompt the user to enter a grade in the class
score = input.nextDouble(); // sets the value of score to the next input double from user
}
double average = total/numberOfScores; // declare variable average and set value to total divided buy the number of scores
System.out.println("The Course Name: " + courseName); //print a messege that shows the user the course name he entered
System.out.println("Number Of Scores: " + numberOfScores); // prints a messege with the number of scores
System.out.printf(" The average score: %.2f" , average); // prints a messege with the average score with only 2 decimal places
System.out.println(); // goes to next line
System.out.printf(" The Minimum score: %.2f" , min);// prints message with minimum score with only 2 decimal places
System.out.println(); // goes to next line
System.out.printf(" The Maximum score: %.2f" , max); // prints messege with maximum score with only 2 decimal places
System.out.println();// goes to next line
input.nextLine(); //read the end of the line and throw it away
}

This code will do the work please ask me if you feel confused :
Scanner input = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<Integer>();
System.out.println("Please enter the name of the course:");
String course=input.next();
System.out.println("Please enter the scores for CSC 201 on a single line and type a -1 at the end");
int max=0;
int min=Integer.MAX_VALUE;
int sum=0;
int grade;
that: while(true){
grade=input.nextInt();
if(grade==-1)
break that;
list.add(grade);
sum=sum+grade;
if(grade>max)
max=grade;
if(grade<min)
min=grade;
}
System.out.println("The course name: "+ course);
System.out.println("Number of Scores :"+list.size());
System.out.println("The Average Score :"+(double)sum/list.size());
System.out.println("The Minimum Score: "+min);
System.out.println("The Maximum Score :"+max);
PS : Integer.MAX_VALUE is a huge value maybe 100 is good if the limit of the grade is 100.
why using linked list ?
because it's easy to store the values one by one .
I can reach all elements when ever i want.
also the method size of this list is the number of elements it has so I don't need a counter to count how many grades i have .
also you can print them after that if you want because all grades now are stored in this list.
if you don't need these grades in something next , you can ignore the list and do it without it .
Good luck .

Related

What is happening inside the for loop with grade and sum? I have no clue what it's doing

This is a program that calculates the users test average based on how many inputs he wants. But, I do not know what is happening inside the for loop and what it means. The grade and the sum.
System.out.println("Welcome, please type your first name. ");
String name = scan.nextLine();
System.out.println("Welcome, please type your last name. ");
String last = scan.nextLine();
int numberOfTests;
System.out.println("How many tests would you like the average of?");
numberOfTests = scan.nextInt();
while(numberOfTests<0)
{
System.out.println("Invalid input.");
System.out.println("How many tests would you like the average
of?");
numberOfTests = scan.nextInt();
}
double sum = 0;
double grade;
System.out.println("Enter " + numberOfTests + " scores.");
for(int i = 0;i<numberOfTests;i++)
{
grade = scan.nextDouble();
sum += grade;
}
double average = (sum/numberOfTests);
System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", your
average score is " + (average));
System.out.print("Your letter grade is ");
The program works.
It looks like scan is an instance of java.util.Scanner. This class is used to read from user input, so grade = scan.nextDouble() reads the next double from the user's input.
Then sum += grade is equivalent to sum = sum + grade; it adds the grade that the user input to the total grade (sum).
So the loop asks for numberOfTests inputs from the user, and adds them all together in sum.
For details for how the input is read, look at the documentation for Scannner#nextDouble().
grade = scan.nextDouble();
This asks the user to input a grade(a double type number)
sum += grade;
Then for each iteration, the input grade is added to sum. So after numberOfTests iterations, sum will contain the sum of numberOfTests grades.
As mentioned by #Goion in comments, sum += grade; is basically sum = sum + grade;
Once you have the sum, you can divide it by numberOfTests to get the average.
The for loop is used here to calculate the sum of all the grades.
What this code does, it asks you to enter numbers according to the total of numberOfTests. Having, i = 0 you enter 2. i = 1 you enter 3. And the sum variable will be accumulating: 2 + 3.
System.out.println("Enter " + numberOfTests + " scores.");
for(int i = 0;i<numberOfTests;i++){
grade = scan.nextDouble();
sum += grade;
}
At the end, sum will be equal to 5.
And finally
double average = (sum/numberOfTests);
average = 5/2 is equal to 2.5.
numberOfTests = scan.nextInt();
Here asking how many tests they want to enter marks. If input value less than 0 asking the value again.
below for loop used to read the number of makes based on the previous input test value
and adding all enter marks
for(int i = 0;i<numberOfTests;i++)
{`enter code here`
}
below statement calculate the average marks (simple calculation total marks / no. of tests)
double average = (sum/numberOfTests);

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

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.

How do you get your program to repeat if input is invalid instead of continuing with invalid input?

I am trying to validate a user input, cuPerTerm > 12
I get the error message but the program continues and uses the invalid input to run
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
I need it to continue to re-ask until 12 or something greater is entered. and then continue the program.
You should use a while loop so that you continue looping until cuPerTerm is at least 12. Remember to take the user input again with cuPerTerm = in.nextInt(); inside the while loop.
Here's a simple solution:
int cuPerTerm = -1; // intialize to an invalid value
while (cuPerTerm < 12) {
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) { //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
}
Add this to continue getting input till it satisfies your condition:
while(cuPerTerm <= 12){
//Ask use to provide input
}
It is simple while loop which checks your input condition and continues taking input till it is satisfied.
Edit: -
Initialize your cuPerTerm =0
while(cuPerTerm <= 12)
{
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
}
There are pitfalls: Simple doing scanner.nextInt() will give you the next Integer of the CURRENT Line.
If the user types in test, nextInt() will throw an InputMismatchException, you have to handle. Also the int will NOT be consumed
So you have to call scanner.nextLine() in between to Clean the current (mismatched) result.
All together something like this:
do{
try
{
System.out.print("Enter number > 12: ");
System.out.flush();
number = scanner.nextInt();
if (number > 12)
done = true;
}
catch(InputMismatchException e) {
System.out.println("This is not a number");
scanner.nextLine() //!Important!
}
}while(!done);
I think that a do-while loop will best suit your needs:
int val;
do {
val = in.nextInt();
} while (val < 12);

Categories

Resources