Some problems with my array - java

my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!

Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}

In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.

Related

Java Array Grading

I was looking for some input on my code. What i'm trying to do is get user input in the form of scores on a test or something. The user can input how many grades they need to enter and it stores them on the array. Then the program will grade on a curve with the highest being an A. if a score is within 10 points of the highest score, it is also an A, if its in between 10 to 20 points less than the higher score its a B, if its 20 to 30 points less than the highest score then its a C, and so on till F.
My issue is that I don't know how to compare a certain element to the highest to see what grade it is. So my question is how do you compare a certain element in an array to the highest element in the array?
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int students;
System.out.println("How many students do you have?");
students = keyboard.nextInt();
while (students < 0) {
System.out.println("Invalid student amount");
students = keyboard.nextInt();
}
int[] kids = new int[students];
double[] scores = new double[students];
for (int index = 0; index < students; index++) {
System.out.println("Enter score for student #" + (index + 1) + ": ");
scores[index] = keyboard.nextDouble();
}
double high = scores[0];
for (int index = 1; index < scores.length; index++) {
if (scores[index] > high) ;
high = scores[index];
}
if (//place in array >= (highest-10)
System.out.println("Student (whatever there position is) has an A")
}
}
So if anyone can give me some insight into this issue I'll be grateful, also if you see anything wrong with the code please tell me. Any help would be great. Just to clarify my issue is with trying to find the letter grade. look at the if statement at the bottom.
If I were you, I would do that in the following way:
public class Student implements Comparable{
int index;
private double grade;
public Student(int i, double d) {
grade = d;
index = i;
}
public int getIndex() {
return index;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
#Override
public int compareTo(Object o) {
Student s = (Student)o;
if (s.getGrade() < grade){
return -1;
} else if (s.getGrade() == grade) {
return 0;
}
return 1;
}
}
And the driver for the application is:
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int amount;
System.out.println("How many students do you have?");
amount = keyboard.nextInt();
while (amount < 0) {
System.out.println("Invalid student amount");
amount = keyboard.nextInt();
}
Student[] students = new Student[amount];
for (int index = 0; index < amount; index++) {
System.out.println("Enter score for student #" + (index + 1) + ": ");
students[index] = new Student(index, keyboard.nextDouble());
}
Arrays.sort(students);
for (int i = 0; i < amount / 10 + 1; i++) {
System.out.println("Student " + (students[i].getIndex() + 1) + " has an A");
}
}
Edit:
additional clarification for the OP asked in comments:
double highest = students[0].getGrade();
for (Student s : students) {
if (s.getGrade() > highest) {
highest = s.getGrade();
}
}

how do i add 3 salaries using array index?

I need help getting total amount for salary using printf statement
numbers/salary i need to add to get total salary;
salary 1: 120000.00
salary 2: 200500.00
salary 3: 175000.50 total
payroll amount is $495501.49
I need help getting total and the code to get the total payroll amount
This is my code:
import java.util.Scanner;
public class LabSeven {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[3];
Double []dollarSalary= new Double[3];
double sum= 0;
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
}
double total= sum + dollarSalary;
System.out.printf("Total payroll amount is: %7.2f\n", sum);
for(int i=0; i<=3; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}
After this line:
dollarSalary[i]=input.nextDouble();
Add this line:
sum += dollarSalary[i];
This way you will be accumulating the sum in the sum variable.
And, delete this line, as you cannot add an array to a double value, this statement made no sense:
double total= sum + dollarSalary;
Finally, you have one more bug, here:
for(int i=0; i<=3; i++) {
The problem is that i will take values 0, 1, 2, 3, but the size of the arrays is 3, so the only valid values are 0, 1, 2. Change the condition to < instead of <=:
for(int i=0; i<3; i++) {
Extra tips
Don't use a Double[]. A double[] is enough for your purpose here
Don't write the number 3 repeatedly. Define a constant, for example private static final PLAYERS_NUMand use this everywhere instead. That way if you want to change the number of players later, you can do it in one place instead of 4
Format your code nicely. Use an IDE like IntelliJ or Eclipse, and use their auto-format features
Putting it together
With the above suggestions applied, your program becomes:
public class LabSeven {
private static final int PLAYERS_NUM = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[PLAYERS_NUM];
double[] dollarSalary = new double[PLAYERS_NUM];
double totalSalary = 0;
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.print("Enter player name: ");
playerName[i] = input.next();
System.out.print("Enter Salary: ");
double salary = input.nextDouble();
dollarSalary[i] = salary;
totalSalary += salary;
}
System.out.printf("Total payroll amount is: %7.2f\n", totalSalary);
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}
Use this line in your for-loop and remove your total variable you don't need this.
sum += input.nextDouble();
or
sum += dollarSalary[i];
You can't add an array to a variable like you're doing.
Do something like this to add the salaries from your array. In your for after you add an individual salary to your dollarSalary add it to your sum variable as well.
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
sum += dollarSalary[i]
//sum += input.nextDouble(); This expects another input from the user. We should not be doing this.
}
//double total= sum + dollarSalary; You dont need this line anymore
System.out.printf("Total payroll amount is: %7.2f\n", sum);

Ending a program with ctrl+Z

import java.util.Scanner;
public class ClassAverage
{
public static void main(String args[])
{
String names[] = new String[50];
int scores[] = new int[50];
int entries = 0;
Scanner in = new Scanner(System.in);
//System.out.println("Enter number of entries");
//int entry = in.nextInt();
System.out.println("Enter the names followed by scores of students: ");
for(int i = 0; i < 50; i++)
{
names[i] = in.next();
scores[i] = in.nextInt();
entries++;
}
Average avg = new Average();
double average = avg.CalcAvg(scores,entries);
System.out.println("The class average is: " + average);
avg.belowAvg(scores,average,names,entries);
avg.highestScore(scores,names, entries);
}
}
class Average
{
Average()
{
System.out.println("The averages: ");
}
double CalcAvg(int scores[], int entries)
{
double avg;
int total = 0;
for(int i = 0; i < entries; i++)
{
total += scores[i];
}
avg = total/entries;
return avg;
}
void belowAvg(int scores[],double average,String names[], int entries)
{
for(int i = 0; i < entries; i++)
{
if(scores[i] < average)
System.out.println(names[i] + "You're below class average");
}
}
void highestScore(int scores[],String names[], int entries)
{
int max = scores[1];
for(int i = 0; i < entries; i++)
{
if(scores[i]>=max)
max=scores[i];
}
System.out.println("The maximum score is: " + max);
System.out.println("The highest score acheivers list: ");
for(int i = 0; i < entries; i++)
{
if(scores[i] == max)
System.out.println(names[i]);
}
}
}
im suppose to hold the ctrlkey press z and then press the enter key to end the program but how do i do that?
if you are wondering the program is to write a program that lets the user input student names followed by their test scores and outputs the class average, names of students below the average, and the highest test score with the name of student
Ctrl-Z is the DOS command code for end of input (the UNIX equivalent is Ctrl-D). All command line programs should support this because it allows you to pipe output from one as input to the other. Kudos to your teacher!
When this key combo is pressed, Scanner.hasNextLine() will return false. Here's an example of a loop that reads line until you hit Ctrl-Z on Windows (or Ctrl-D on Linux/Unix):
while (in.hasNextLine()) {
System.out.println("You wrote " + in.nextLine());
}
You can listen for the control-z character in your scanner:
String nextLine = in.nextLine();
if(nextLine.length == 1 && nextLine.charAt(0) == KeyEvent.VK_Z)
// end program

Min and Max Values [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have to make code to find the max, min, and average of grades. This is what I have so far:
public class test
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, grades, max=0, min=0;
final int = MAX_GRA = 0
final int = MIN_GRA = 0
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grades = scan.nextInt();
while (grades != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grades;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grades = scan.nextInt();
}
System.out.println ();
if (count == 0) //An if statement that identifies if no numbers were entered
System.out.println ("No grades were entered.");
else //An else statement that computes that computes the average
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
}
}
}
Any ideas? I'm new to java and coding in general. Thank you for your time!
You could try something like this:
int maxGrade = 0;
int minGrade = 10; // Set the highest possible grade.
while (grades != 999)
{
// If the current grade is greater that the maxGrade,
// set this value the maxGrade.
if(grades > maxGrade)
maxGrade = grades;
// If the current grade is less than the minGrade,
// set this value to the minGrade.
if(grades < minGrade)
minGrade = grades;
// Here you will place the rest of your code.
}
Note: Try to use more meaningful names for your variables. This will make your code more readable and it convey far easier your intentions and thoughts to the reader of your code. For instance, since grades would keep the value of the current grade, it would be more reasonable to name it as grade.
Update
As correctly laune mentioned below you could make use of two methods of Math class, in order to avoid the if statements.
while (grades != 999)
{
maxGrade = Math.max(maxGrade, grades);
minGrade = Math.min(minGrade, grades);
}
I would change somethings in the original code, and put like this.
public class Grades {
// MODIFIERS (final, private, protected, static, etc.) type (int, double,
// float, Object, etc.) name [= initialValue];
private final static double END_GRADES = 999;
public static void main(String[] args) {
double count, sum, grades, max, min;
Scanner scan = new Scanner(System.in);
// Initialized data.
count = 0;
sum = 0;
max = 0;
min = 0;
do {
System.out.println("Enter next grade ("+(int)END_GRADES+" to quit):");
grades = scan.nextDouble();
if (grades != END_GRADES) {
if (count == 0) { // First grade is always min.
min = grades;
}
sum = sum + grades;
count++;
System.out.println("The sum so far is: " + sum);
if (max < grades) { // New max??
max = grades;
}
if (min > grades) { // New min??
min = grades;
}
}
} while (grades != END_GRADES);
if (count != 0) {
System.out.println("The average grade is: " + (sum / count));
System.out.println("The max grade is: " + max);
System.out.println("The min grade is: " + min);
} else {
System.out.println("No grades were entered.");
}
}
}
Look like you took half the way to the answer, but I assume you are missing the min,max values as you average and sum are already computed.
First you need to add two instruction to update your maximum and minimum variables grade holders and the short way to do is to use:
Math#max shorthand comparison returning the max of arguments.
Math#min shorthand comparison returning the min of arguments.
But you have to remove the final modifier in front of the MAX_GRA and MIN_GRA because those instance variables need to be update at each iteration in your while loop so that they get either the user entered grade or keep their own value.
You should then take care of variables declaration, so that comparisons will take place and to do so, you can set the min value to the maximum possible one in the integer range and vice vers ça.
Last you need to add print statement simply to show you max / min value along with your average of grades:
public class MinMaxAndAverageCalculator
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, max=0, min=0;
int MAX_GRA = Integer.MIN_VALUE;
int MIN_GRA = Integer.MAX_VALUE;
int grade;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grade = scan.nextInt();
while (grade != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grade;
MAX_GRA = Math.max(grade, MAX_GRA);
MIN_GRA = Math.min(grade, MIN_GRA);
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grade = scan.nextInt();
}
if (count == 0) //An if statement that identifies if no numbers were entered
{
System.out.println("No grades were entered.");
}
else //An else statement that computes that computes the average
{
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
System.out.println ("The maximum grade is " + MAX_GRA);
System.out.println ("The minimum grade is " + MIN_GRA);
}
}
}

Loop not quite working java

I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}

Categories