My programs print statement is wrong - java

When i run my program and choose a number between 0 and 100, it prints my answer wrong.
Java console
----jGRASP exec: java TestScores
How many tests do you have? 3
Enter grade for Test 1: 80
Enter grade for Test 2: 80
Enter grade for Test 3: 80
The average is: 26.666666666666668The average is: 53.333333333333336The average is: 80.0
----jGRASP: operation complete.
import java.util.Scanner;
public class TestScores {
public static void main(String[] args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index] > 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
average = totGrades / grade.length;
System.out.print("The average is: " + average);
}
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}

You print the average inside the loop that calculates the average.
Print it only outside the loop.

You should calculate sum in loop and then (after the loop) divide it by the number of elements.

I move the statement which calculates the sum from inside the loop to the outside, that works.
My new code is.
import java.util.Scanner;
public class TestScores
{
public static void main(String[]args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++)
{
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You can close my post.

Related

Creating a method which specifically calculates the average of the users entered values

I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;

I want to print how many number is greater than the average

I already print the total and average. However I can't print how many numbers is greater than average.
I think the problem is the number>= average, it seems like only adding the last input.
public static void main(String[] args) {
int i;
int number = 0;
double total=0;
double average=0;
int aboveaverage=0;
Scanner read = new Scanner (System.in);
for(i=1;i<9;i++){
System.out.print("Enter number " + i +": ");
number=read.nextInt();
if(number<0){
System.out.println("Invalid Input");
break;
}
total+=number;
}
if(number>=average){
aboveaverage+=1;
System.out.println("Greater than average is :" + aboveaverage);
}
average=total/8;
System.out.println("Print total : "+ total);
System.out.println("Print Average : " +average );
}
}
You will need to collect all numbers (by placing them in an int array), and iterate over all numbers, for example inside a for loop.
public static void main(String[] args) {
int i;
int number = 0;
int numberCount = 8;
int[] numberArray = new int[numberCount];
double total = 0;
double average = 0;
int aboveAverage = 0;
Scanner read = new Scanner (System.in);
for(i = 0; i < numberCount; i++){
System.out.print("Enter number " + (i + 1) + ": ");
number = read.nextInt();
if(number < 0){
System.out.println("Invalid input");
continue;
}
numberArray[i] = number;
total += number;
}
average = total / numberCount;
for(i = 0; i < numberCount; i++){
if(numberArray[i] > average) {
aboveAverage++;
}
}
System.out.println("Count of numbers greater than average: " + aboveAverage);
System.out.println("Print total: " + total);
System.out.println("Print average: " + average);
}

Why isn't my Java number input code working?

I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}

Java Change Prompt Order

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

How do you stop a loop from running in Java

How do you stop a conditional loop from running. For example if I write an if statement that accepts values from 0 to 100. How do stop the program if a user enters a number less then 0 or above 100.
import java.util.Scanner;
public class TestScores {
public static void main(String[]args) {
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++) {
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100) {
try {
throw new InvalidTestScore();
}
catch (InvalidTestScore e) {
e.printStackTrace();
}
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
You use the
break;
keyword. This breaks out of a loop.
You may want to use break
for(int i=0; i<100; i++)
{
if(user entered invalid value)
break; // breaks out of the for loop
}
Here's a hint, since this looks like homework to me: you can either use the break keyword, or use this condition:
if (grade[index] < 0 || grade[index]> 100)
{
// invalid grade...
}
as part of the loop condition.

Categories

Resources