Is it possible to make this output in Java?
Using Looped statements while asking for input Grades for each student then use Ceiling to identify who has the highest grade.
Student Number Grades
Student 1 _
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Student 8
Student 9
Student 10
The student with the highest Grade is: (e.g) Student 8
Yes, you can use a loop:
Scanner scan = new Scanner(System.in);
double max = -1; // grades can't be negative
int maxStudent = 0;
double[] grades = new double[10];
for (int i = 1; i < grades.length; i++) {
System.out.println("Please enter grade for Student "+i);
grades[i] = scan.nextDouble();
if (grades[i] > max) {
max = grades[i]
maxStudent = i;
}
}
Math.ceil(double a)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. So unless you're trying to round up, you won't need ceil. Although to answer the title question, you can use Math.ceil on an input string, assuming the string can be parsed into a double.
For instance, these are all true statements:
Math.ceil(99) == 99.0
Math.ceil(99.01) == 100.0
Math.ceil(99.99) == 100.0
Can ceiling only be used in one number? or it can be used with multiple numbers like that.
You can not use Math.ceil on any sort of collection to find the highest value as you wish to do. Loop through all values an keep track of the highest
Related
I am making a program that accepts user input to subtract all the numbers desired by the user
I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count<=inputNum; Count++), so that the program loops for user input, based on the inputNum.
Unfortunately, the output is wrong. I can't understand how this would work properly.
I've tried switching the operator in difference by making difference =- toBeSubtracted; into difference -= toBeSubtracted;
For difference =- toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -5
For difference -= toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -15
Here is the code:
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
int toBeSubtracted = scan.nextInt();
difference =- toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
Ok this might help you out:
difference = 0
and than you have:
difference -= toBesubtracted
so what you are doing is:
difference = difference - toBeSubtracted
which in terms is
difference = 0 - 10
difference = -10 - 5
thus you get -15
and where you have
difference =- toBeSubtracted
it is the same as
difference = -1 * toBeSubtracted
thus you get -5
I suppose you want output of 5. Here is your code with one change
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = scan.nextInt(); // so read in the first number here.
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1;Count<inputNum; Count++) // go till from 1 to inputNum - 1 because you have already got one number above
{
int toBeSubtracted = scan.nextInt();
difference -= toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
You need to understand the operator shorthand notation. You should write -= for minus shorthand. The shorthand is equal to difference =difference - tobesubstracted. Since your initial value is 0 it becomes 0-10-5= -15.
Assign the first value as difference and then do the substraction of next values.
So something like:
difference = scanner.nextInt();
And then do the loop for rest of the values to minus from initial value.
The problem isn’t that your program is working incorrectly.
The problem is that the requirements are nonsense. You can have the difference between two numbers. The difference between 19 and 8 is 11. There is no such thing as the difference between 3 or more numbers. Therefore no program could ever produce that.
That said, Davis Herring is correct in the comment: there is no =- operator. You tried to use one in the line:
difference =- toBeSubtracted;
But the line is understood as just:
difference = -toBeSubtracted;
So your program just outputs the negative of the last entered number. I tried entering three numbers, 11, 3 and 5. The first time through the loop difference is set to -11. Next time this value is overwritten and -3 is set instead. In the final iteration the difference is set to -5, which “wins” and is output.
Instead I suggest that your program should always subtract 2 numbers, as you are also trying in your example. So the user needs not enter the number of numbers, but is just told to enter the two numbers. Then you also don’t need any loop. Just read the first number, read the second number, subtract the second from the first (or the first from the second, or the smaller from the larger, what you want) and print the result. I am leaving the coding to you to avoid spoiling it.
I did this
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
int currentNumber = 0; //current number from scanner
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
if(Count == 1)
{
//nothing to subtract if count is 1
currentNumber = scan.nextInt();
difference = currentNumber;
}
else {
currentNumber = scan.nextInt();
difference = difference - currentNumber;
}
}
System.out.println("The difference of those numbers is " + difference);
}
}
You started your difference at 0. So if you subtracted two numbers, 15 and 3, then you would get 0 - 15 - 3 = -18. I set the difference equal to the first number, 15 in the first loop. Then it should work correctly because you do 15 - 3 = 12.
I wrote the below code everything works fine except it never executes the last loop so the last value inputted is never calculated into the min/max/average.
Any idea where I went wrong?
import java.util.Scanner;
public class Program4_JohnHuber {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
double total = 0;
//double numbers = 0;
int count = 1;
double largest = 0;
double smallest = Double.MAX_VALUE;
double average = 0;
System.out.print ("Please enter the grades, (Press enter when finished): ");
{
while (input.hasNextDouble()&& count<5)
{
double entered = input.nextDouble();
total = total + entered;
//count++;
//double average = 0;
if (count > 0)
{
average = total/count;
}
if (entered > largest)
{
largest = entered;
}
if (entered < smallest)
{
smallest = entered;
}
count++;
}
}
System.out.printf ("Your average grade is %3.2f,\n", average);
System.out.printf ("Your highest grade is %3.2f \n", largest);
System.out.printf ("Your lowest grade is %3.2f \n", smallest);
}
}
There are two errors in your program (assuming your intent is to input 5 numbers):
You're using count to indicate the number of grades you've entered already. Before you've entered any grades, how many grades have you entered? That's the value count should have, but you've initialized it to the wrong value.
The other issue is in how you've written the while:
while (input.hasNextDouble() && count<5)
Suppose you've fixed the first problem, so that it now lets you enter 5 numbers and keeps statistics on those numbers. Now it goes back up to the while loop and evaluates the boolean expression.
At this point, count is 5, so you want to exit the loop. But that doesn't happen, because input.hasNextDouble() is evaluated first. Since you're using a scanner on System.in, that means that the program waits until either you type in something that isn't blank, or until you indicate the end of input with CTRL+D on Linux or CTRL+Z on Windows. After it finds the next item in the input, it will then exit the loop if it can't find a double (e.g. you type in some letters); or if you put in a double, then it checks count.
The combination of these two errors is why the program appears to be ignoring the last input: (1) it only does the computation on 4 grades, not 5, because of the error in initializing count, and (2) it asks for a 5th grade anyway, because the parts of the while loop condition are in the wrong order.
To fix the second problem, change it to
while (count < 5 && input.hasNextDouble())
This checks count first, and exits the loop immediately when you have enough grades, instead of looking for more input.
I am learning Java on my own and have just finished learning the basics of arrays, or so I think. I want to create a class grade sheet that keeps each student's grades and average. I have a for loop that asks each of the 10 students to enter their 4 test grades. Once I get those 4 grades, I take the average. I then store the student's grades and average into an array, one array per student. I essentially create 10 arrays with these 5 elements, for each student using the for loop. I now want to take the 5th element, the average of the 4 grades, from each student's array and populate another array called averages so I can perform other calculations. Is this possible with my logic? I think I could hard code 10 arrays, 1 for each student like so:
double averages[] = {student1[4], student2[4], ..., student10[4]};
Isn't this a bad way to go about this though? Any constructive help or guidance would be appreciated. Please do not post code that gives away the answer, as I won't learn from that. I just want a hint in the right direction. :)
Here's my code up until the point of confusion:
import java.util.Scanner;
public class ClassAverages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double grade1 = 0.0, grade2 = 0.0, grade3 = 0.0, grade4 = 0.0, average = 0.0;
// get grades from each of the 10 students
for (int student = 1; student <= 3; student++) {
System.out.println("Student " + student);
System.out.println("---------\n");
System.out.print("Enter the first grade: ");
grade1 = keyboard.nextDouble();
while (grade1 < 0) { // input validation for grade 1
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade1 = keyboard.nextDouble();
}
System.out.print("Enter the second grade: ");
grade2 = keyboard.nextDouble();
while (grade2 < 0) { // input validation for grade 2
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade2 = keyboard.nextDouble();
}
System.out.print("Enter the third grade: ");
grade3 = keyboard.nextDouble();
while (grade3 < 0) { // input validation for grade 3
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade3 = keyboard.nextDouble();
}
System.out.print("Enter the fourth grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
while (grade4 < 0) { // input validation for grade 4
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
}
// calculate the current student's average
average = (grade1 + grade2 + grade3 + grade4) / 4;
// for each student, 1 to 10, create an array with their 4 grades and average
double studentX[] = { grade1, grade2, grade3, grade4, average };
System.out.println("SCORE 1\t\tSCORE 2\t\tSCORE 3\t\tSCORE 4\t\tAVERAGE");
System.out.print(studentX[0] + "\t\t");
System.out.print(studentX[1] + "\t\t");
System.out.print(studentX[2] + "\t\t");
System.out.print(studentX[3] + "\t\t");
System.out.print(studentX[4] + "\n");
System.out.println();
// I want to use each student's average for each corresponding element in the averages array
// create an array of all student's averages
// double averages[] = {student1average, student2average,...student10average} ???
}
}
}
OUTPUT AS OF NOW:
Student 1
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 100
Enter the fourth grade: 100
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 100.0 100.0 100.0
Student 2
---------
Enter the first grade: 90
Enter the second grade: 90
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
90.0 90.0 90.0 80.0 87.5
Student 3
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 90.0 80.0 92.5
You could use a for loop. However this will require you to have a collection of items to iterate through. I think the best way for you to do this is to organize your students into their own separate class (give that class all the grades as parameters in its constructor and have it do the calculations for average within that class).
So if you call your class student then your constructor could look like thisstudent(int grade1, int grade2, int grade3, int grade4). Use these parameters to calculate the average for each student object.
Then in your ClassAverage class just instantiate new student objects as you want and add them to an array of student objects and then its as simple as iterating through the array of student, extracting the average field that you created for each student object (extract this simply by stating studentName.average, assuming you named your average field average in the student class).
So by the end you should have something that looks like this. Let's assume that the array of student objects is called studentArray
int[] averageArray = new int[studentArray.length];
for (int i = 0; i < studentArray.length; i++){
averageArray[i] = studentArray[i].average;
}
Good luck!
Arrays are very bad form of storing information. Mostly because they don't contain logic that uses data inside this arrays and any other code can make that data invalid because array doesn't check what values you give it. This is what classes are for: to have data and code that works with it in one place, and to protect data from changes from other places in code.
So for your case arrays are OK for fields of the same type(for example, array of students is OK), but not for values of that types(array of arrays of students grades is NOT OK). So what you should do here is to use a class:
class Student
{
int grades[] = new int[4];
public Student(int grade1, grade2, int grade3, int grade4)
{
grades[0] = grade1;
grades[1]=grade2;
grades[2]=grade3;
grades[3]=grade4;
}
public double average()
{
double result = 0;
for(int i =0; i<grades.count; i++)
result += grades;
return result / grades / count;
}
// and so on
}
They allow you to take logic inside object, sou you can use it like this:
Student albert = new Student(5, 4, 2, 1);
System.out.println(albert.avarage()); // prints 3
I have a question about how to break out of a loop so as not to include a value. I am supposed to enter a few integer amounts to represent grades on a test and then break out of the loop when a value of "0" is entered. However I do not want 0 to be included in the calculation of the average and the minimum. That is a little vague so here is my code.
import java.util.*;
import java.lang.*;
public class Grades
{
public static void main (String[] args)
{
Scanner myScan= new Scanner(System.in);
String input="Input numerical grade:";
System.out.println(input);
int sum=0;
int count= 0;
int max= 0;
int min= 0;
double avg=0;
boolean notNull= true;
while(notNull== true)//While grades are greater than 0 ask the question again
{
int grade= myScan.nextInt();
if(grade==0)break;
if(grade>max)
{
max=grade;
}
if(grade<min)
{
min=grade;
}
System.out.println(input);
sum +=grade;
count++;
avg= (sum)/(count);
}
System.out.println("Maximum:"+max);
System.out.println("Minimum:"+min);
System.out.println("Average:"+avg);
}
}
And here is my return when I enter a few random test scores and 0. So instead of 0 I want my minimum to be 47.
----jGRASP exec: java Grades
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:0
Average:71.0
----jGRASP: operation complete.
You don-t take into account that you've initialized min with zero so:
if(grade<min)
{
min=grade;
}
will never change minbecause it is already minimal non-negative integer - zero.
So take this into account with following condition:
if(min == 0 || min < grade)
{
min=grade;
}
The 0 your program is printing out isn't the 0 the user enters. It's the 0 you initialize min to. (Currently, your average is being properly calculated.)
if(grade<min)
{
min=grade;
}
min's original value is 0. So unless you're taking negative grades, grade<min will never evaluate to true.
Instead of int min = 0;, you should do this:
int min = Integer.MAX_VALUE;
Also, as I commented, because you're never touching the boolean you use as the while loop conditional check, and you're only wanting to exit the loop when the user enters 0, you can just drop the entire variable, and use while(true).
It looks like you're already breaking out of your loop before processing the 0. The reason your minimum is 0 is because you initialized it to 0, and so of course if (grade<min) { min=grade; } will never happen for any positive grade.
You have a few options:
You could set min = max = grade directly for the first grade that is input.
You could initialize min to a large number that any reasonable grade would be less than, e.g. Integer.MAX_VALUE.
You have a few possibilities for an implementation of the first option. You could store some first flag that you initialize to true then set to false. You could maintain a count of the number of grades input and initialize min/max when the count is 0 (or 1 depending on how you do it). You could initialize min/max to some special flag values that a grade could never be, e.g. -1, and set them to grade directly when they equal that flag value.
The point here is that the reason you are seeing 0 for your minimum isn't because you're processing that final 0, it's because you initialize your minimum to 0, and no grade is lower than that.
You probably want somthing like this:
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String input = "Input numerical grade:";
System.out.println(input);
int grade = myScan.nextInt();
int sum = 0;
int count = 0;
int max = grade;
int min = grade;
double avg = grade;
while (grade != 0) {
if (grade > max) {
max = grade;
}
if (grade < min) {
min = grade;
}
count++;
sum += grade;
avg = (sum) / (count);
System.out.println(input);
grade = myScan.nextInt();
}
System.out.println("Maximum:" + max);
System.out.println("Minimum:" + min);
System.out.println("Average:" + avg);
}
}
Puts out:
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:47
Average:71.0
This program will calculate the average grade for 4 exams using a for loop by prompting
the user for exam grades, one at a time, then calculate the average and display the result.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i <= 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
if (i == 4) {
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
}
}
} // end main ()
} // end class ExamsFor4
My result:
Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.
This would be correct except for the last print out of: 'Please enter the next exam: 96'
I tried putting the IF statement between the 'sum' line and the TextIO.put 'Enter next exam', but that isolates it.
Thanks, from a Network Dude trap in a Programmer's world.
You have what is called an off-by-one error, compounded by the fact that you're convoluting your loop logic unnecessarily.
With regards to the loop, I recommend two things:
Don't loop for (int i = 1; i <= N; i++); it's atypical
Do for (int i = 0; i < N; i++); it's more typical
Instead of checking for the last iteration to do something, refactor and take it outside of the loop
Related questions
What is exactly the off-by-one errors in the while loop?
See also
Wikipedia/Off-by-one error
On Double Avg
In Java, variable names start with lowercase. Moreover, Double is a reference type, the box for the primitive double. Whenever possible, you should prefer double to Double
See also
Java Language Guide/Autoboxing
JLS 5.1.7 Boxing Conversion and 5.1.8 Unboxing Conversion
Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives
Related questions
What is the difference between an int and an Integer in Java/C#?
Java: What’s the difference between autoboxing and casting?
Why does int num = Integer.getInteger(“123”) throw NullPointerException?
Why does autoboxing in Java allow me to have 3 possible values for a boolean?
Is it guaranteed that new Integer(i) == i in Java? (YES!!!)
When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
Java noob: generics over objects only? (yes, unfortunately)
Rewrite
Here's a way to rewrite the code that makes it more readable. I used java.util.Scanner since I don't think TextIO is standard, but the essence remains the same.
import java.util.*;
public class ExamsFor4 {
public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
final int NUM_EXAMS = 4;
int sum = 0;
for (int i = 0; i < NUM_EXAMS; i++) {
System.out.printf("Please enter the %s exam: ",
(i == 0) ? "first" : "next"
);
sum += sc.nextInt();
}
System.out.printf("Total is %d%n", sum);
System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
}
}
An example session is as follows:
Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25
Note that:
Only necessary variables are declared
The loop index is local only to the loop
There are no cluttering comments
Instead, focus on writing clear, concise, readable code
If it makes sense to make something final, do so
Constants in Java is all uppercase
Related questions
Why does (360 / 24) / 60 = 0 in Java
Because it performs integer division. This is why the cast to (double) prior to the division in above code is necessary, so that it performs floating point division.
How does the ternary operator work?
This is the ?: operator in above code, also known as the conditional operator.
See also: JLS 15.25 Conditional Operator ?:
Change your end condition to be strictly less than 4 and put the code that prints out the total and average outside the loop.
You should probably put the if-statment outside the for-loop. That way you don't need the if-statement. Second the statement in the loop should be < 4 instead of <= 4.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i < 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
} // end main ()
}
Just making few changes in your code makes it work. But you should follow cleaner approach as proposed in some of answers.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber;
for ( i = 1; i < 4; i++ ) {
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber; // Add inputNumber to running sum.
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
} // end main ()
} // end class ExamsFor4
import java.util.Scanner;
public class ExamsFor4 {
public static void main(String[] arguments) {
int sum = 0; // The sum of the exams.
int i = 1; // Number of exams.
double avg = 0; // The average of the exams.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the first exam: ");
sum += in.nextInt();
i++;
while(i<=4){
System.out.print("Please enter the next exam: ");
sum += in.nextInt();
if(i==4)
break;// this line is so that it wont increment an extra time.
i++;
}
System.out.println("The total sum for all " + i +" exams is " + sum);
avg = ((double)sum/i);
System.out.println("The average for the exams entered is" + avg);
} // end main ()
} // end class ExamsFor4