Welcome to Dream.In.Code
Become a Java Expert!

Join 150,199 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,995 people online right now. Registration is fast and FREE... Join Now!




Array Confusion

2 Pages V  1 2 >  
Reply to this topicStart new topic

Array Confusion

raeNet
13 Sep, 2008 - 10:39 AM
Post #1

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
I'm having an awful time with arrays. I'm so confused. Can anyone lend some guidance to get me on track?

CODE

import java.util.Scanner; // Needed for Scanner class

/**
   This program uses a String array (or ArrayList object)
to hold the names of 5 students,
an array of 5 characters to hold the student's letter grades, and
five arrays of 4 doubles each to hold their test scores.
    
  Program allows user to enter each student's name and 4 test scores.
    
  Program displays student's name, average test score and letter grade.
*/

public class GradeBook
{
   public static void main(String[] args)
   {
         final int STUDENTS = 5;// Number of students
        final char LETTERS = 5;    // Number of grades
        final int TESTS = 4;    // Number of tests
    
      // Create an array to hold students names.
         String[] names = new String[STUDENTS];
        char[] grades = new char[LETTERS];
        double[] score1 = new double[TESTS];
        double[] score2 = new double[TESTS];
        double[] score3 = new double[TESTS];
        double[] score4 = new double[TESTS];
        double total = 0;
        double average;
        for (int index = 0; index < score1.length; index++)
            total += score1[index];
            average = total / score1.length;
        for (int index = 1; index < score1.length; index++)
            total += score2[index];
            average = total / score1.length;
        for (int index = 2; index < score1.length; index++)
            total += score3[index];
            average = total / score1.length;
        for (int index = 3; index < score1.length; index++)
            total += score4[index];
            average = total / score1.length;
            
        int count = 0;

      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);

      // Get the names of each student.
      System.out.println("Enter student's name: ");
        String student = keyboard.nextLine();
        System.out.println("Enter student's 1st test score: ");
        double test1 = Double.parseDouble(keyboard.nextLine());
        System.out.println("Enter student's 2nd test score: ");
        double test2 = Double.parseDouble(keyboard.nextLine());
        System.out.println("Enter student's 3rd test score: ");
        double test3 = Double.parseDouble(keyboard.nextLine());
        System.out.println("Enter student's 4th test score: ");
        double test4 = Double.parseDouble(keyboard.nextLine());
            {
    
        if(average >=90)
            grade='A';
        else if(average >=80)
            grade='B';
        else if(average >=70)
            grade='C';
        else if(average >=60)
            grade='D';
        else
            grade='F';
        }
        
    }
}

User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Array Confusion
13 Sep, 2008 - 11:26 AM
Post #2

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
Here are some problems in your code:

first, you are never setting the scores arrays, they are initialized to an array length 4, but never have anything set to them.

to create and set a set of scores do something like so:

CODE

//import scanner;
public static void main(String[] args){
  Scanner input = new Scanner(System.in);
  System.out.println("Insert 3 test scores:");
  double[] scores = {input.nextDouble(), input.nextDouble(), input.nextDouble()};
  // taking the average:
  double avg = 0;
  for(int i=0; i<scores.length; i++){
    avg += scores[i];
  }
  avg /= scores.length;
  System.out.println("The average score is: "+avg);
}


second, you keep changing the names of the variables you are suing (which is leading to many errors).

and so on.

Hope that makes some sense.

This post has been edited by BetaWar: 13 Sep, 2008 - 11:27 AM
User is offlineProfile CardPM
+Quote Post

raeNet
RE: Array Confusion
13 Sep, 2008 - 12:17 PM
Post #3

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
Is this what you meant?

CODE

public class GradeBook
{
   public static void main(String[] args)
   {
     final int STUDENTS = 5;// Number of students
     final char LETTERS = 5;    // Number of grades
     final int TESTS = 4;    // Number of tests
    
     // Create an array to hold students names.
     String[] names = new String[STUDENTS];
     char[] grades = new char[LETTERS];
     double[] scores = new double[TESTS];
    
     Scanner input = new Scanner(System.in);

     // Get the names of each student
     System.out.println("Enter student's name: ");
     String student = input.nextLine();
        
     // Get student scores
     System.out.println("Insert 4 test scores:");
     double[] scores = {input.nextDouble(), input.nextDouble(),  input.nextDouble(), input.nextDouble()};
        
     // taking the average:
     double average = 0;
     for(int i=0; i<scores.length; i++)
     {
     average += scores[i];
     }
     average /= scores.length;
     System.out.println("The average score is: "+ average);
}
            {
    
        if(average >=90)
            grade='A';
        else if(average >=80)
            grade='B';
        else if(average >=70)
            grade='C';
        else if(average >=60)
            grade='D';
        else
            grade='F';
        }
        
    }

User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Array Confusion
13 Sep, 2008 - 01:25 PM
Post #4

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
Close, I have cleaned up the code to make it a bit nicer looking. You don't need to worry about the names array or the grades array, each of those will have a single value.

Here it is:

CODE
    public static void main(String[] args){
        char grade;
        Scanner input = new Scanner(System.in);

        // Get the names of each student
        System.out.println("Enter student's name: ");
        String student = input.nextLine();

        // Get student scores
        System.out.println("Insert 4 test scores:");
        double[] scores ={input.nextDouble(), input.nextDouble(), input.nextDouble(), input.nextDouble()};

        // taking the average:
        double average = 0;
        for (int i = 0; i < scores.length; i++){
            average += scores[i];
        }
        average /= scores.length;
        System.out.println("The average score is: " + average);

        if (average >= 90)
            grade = 'A';
        else if (average >= 80)
            grade = 'B';
        else if (average >= 70)
            grade = 'C';
        else if (average >= 60)
            grade = 'D';
        else
            grade = 'F';
        System.out.println(student + " has an " + grade + " in the class.");
    }


NOTE - This is only the main method (function), not the whole class
User is offlineProfile CardPM
+Quote Post

raeNet
RE: Array Confusion
13 Sep, 2008 - 02:16 PM
Post #5

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
Thank you - this has helped me out so much!

To enable user to enter (5) names, each with (4) test scores, do I need input coding similar to the following?

String[] names ={input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine()};
User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Array Confusion
13 Sep, 2008 - 06:59 PM
Post #6

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
Yes, that will work.
User is offlineProfile CardPM
+Quote Post

raeNet
RE: Array Confusion
14 Sep, 2008 - 09:04 PM
Post #7

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
Well, I'm able to add five names now, but only one set of scores.

I want to be able to add the (1st) name & (4) test scores, (2nd) name & (4) test scores, etc., and then display the names, grades & averages.

Can anyone help me out with this?




CODE

import java.util.Scanner; // Needed for Scanner class
public class GraBook
{
   public static void main(String[] args)
   {

        final int STUDENTS = 5;// Number of students
        final char LETTERS = 5;    // Number of grades
        final int TESTS = 4;    // Number of tests
    
      // Create an array to hold students names.
       char[] grades = new char[LETTERS];
        double[] score1 = new double[TESTS];
        double[] score2 = new double[TESTS];
        double[] score3 = new double[TESTS];
        double[] score4 = new double[TESTS];
        char grade;
        
    Scanner input = new Scanner(System.in);

    // Get the names of each student
    System.out.println("Enter student's name: ");
    String student = input.nextLine();
    String[] names ={input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine()};

    // Get student scores
    System.out.println("Insert 4 test scores:");
    double[] scores ={input.nextDouble(), input.nextDouble(), input.nextDouble(), input.nextDouble()};

    // Average 4 test scores:
    double average = 0;
    for (int i = 0; i < scores.length; i++)
    {
    average += scores[i];
    }
    average /= scores.length;

    if (average >= 90)
    grade = 'A';
    else if (average >= 80)
    grade = 'B';
    else if (average >= 70)
    grade = 'C';
    else if (average >= 60)
    grade = 'D';
    else
    grade = 'F';

    System.out.println(student + " has a(n) " + grade + " with an average test score of " + average);
}
}

User is offlineProfile CardPM
+Quote Post

raeNet
RE: Array Confusion
15 Sep, 2008 - 12:11 PM
Post #8

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
I've tried about every loop to enable user to enter
1st Student Name, 4 Test Scores
2nd Student Name, 4 Test Scores
...
5th Student Name, 4 Test Scores, but even without errors, I can only get user to input
1st - 5th Name
1 set of test scores

Does anyone have any suggests?
Thanks in advance!
CODE

import java.util.Scanner; // Needed for Scanner class
public class GraBook
{
public static void main(String[] args)
{

final int STUDENTS = 5;// Number of students
final char LETTERS = 5; // Number of grades
final int TESTS = 4; // Number of tests

// Create an array to hold students names.
char[] grades = new char[LETTERS];
double[] score1 = new double[TESTS];
double[] score2 = new double[TESTS];
double[] score3 = new double[TESTS];
double[] score4 = new double[TESTS];
char grade;

Scanner input = new Scanner(System.in);

// Get the names of each student
for (int i=0; i < names.length; i++)
{
System.out.println("Enter student's name: " +
    (i + 1) + ": ");;
String[i]  = keyboard.nextString();


// Get student scores
System.out.println("Insert 4 test scores:");
double[] scores ={input.nextDouble(), input.nextDouble(), input.nextDouble(), input.nextDouble()};


// Average 4 test scores:
double average = 0;
for (int i = 0; i < scores.length; i++)
{
average += scores[i];
}
average /= scores.length;

if (average >= 90)
grade = 'A';
else if (average >= 80)
grade = 'B';
else if (average >= 70)
grade = 'C';
else if (average >= 60)
grade = 'D';
else
grade = 'F';

System.out.println(student + " has a(n) " + grade + " with an average test score of " + average);
}
}

}

User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Array Confusion
15 Sep, 2008 - 02:20 PM
Post #9

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
Sadly Java doesn't seem to allow you to have multi-dimensional arrays, so we have to make a new class to hold things.

Here is the code I came up with:

Student.java:
CODE
import java.util.Scanner;

public class Student{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        Record[] students = {new Record(), new Record(), new Record(), new Record(), new Record()};
        for(int x=0; x<5; x++){
            if(x>0){
                input.nextLine();
            }
            System.out.println("Insert student name:");
            students[x].setName(input.nextLine());
            System.out.println("Insert 5 scores:");
            double[] scores = {input.nextDouble(), input.nextDouble(), input.nextDouble(), input.nextDouble(), input.nextDouble()};
            students[x].setScores(scores);
            System.out.println(students[x].getAvg());
        }
        
        for(int i=0; i<students.length; i++){
            System.out.println("Student entry #"+i+". Name "+students[i].getName()+" Average Test Score "+students[i].getAvg());
        }
    }
}


Record.java:
CODE
public class Record{
    private String myName;
    private double[] myScores;
    public Record(String name, double[] scores){
        myName = name;
        myScores = scores;
    }
    public Record(String name){
        myName = name;
    }
    public Record(double[] scores){
        myScores = scores;
    }
    public Record(){
        myName = "";
    }
    public double getAvg(){
        double sum = 0;
        for(int i=0; i<myScores.length; i++){
            sum += myScores[i];
        }
        sum /= myScores.length;
        return sum;
    }
    public String getName(){
        return myName;
    }
    public void setName(String name){
        myName = name;
    }
    public void setScores(double[] scores){
        myScores = scores;
    }
    public void addScore(double score){
        myScores[myScores.length] = score;
    }
}


Basicall, the Student class has the main method and creates an array of Records. The records each have an array of test scores, myScores, that can be set.

Hope that helps.
User is offlineProfile CardPM
+Quote Post

riwillia
RE: Array Confusion
15 Sep, 2008 - 03:36 PM
Post #10

New D.I.C Head
*

Joined: 15 Sep, 2008
Posts: 3



Thanked: 1 times
My Contributions
To declare multi-dimensional arrays in Java, use multiple square brackets [].


[code] double [][] tests = new double [STUDENTS][TESTS]; [\code]


When you prompt for data,save immediately to an array location instead of a variable. Use an outer loop to prompt for the name. After saving a name, use an inner loop to prompt and save the values for test scores into the proper location in your two-dimensional array for storing test scores.

When you finish your outer loop, you will have stored all scores. The next step would be to sum all scores in your two-dimensional array and calculate the average.

User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Array Confusion
15 Sep, 2008 - 04:20 PM
Post #11

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
QUOTE
To declare multi-dimensional arrays in Java, use multiple square brackets [].



Thanks smile.gif
I try to help people out as best I can, but I am currently learning Java as well, which makes it a little hard to do things sometimes.

Thanks again smile.gif
User is offlineProfile CardPM
+Quote Post

raeNet
RE: Array Confusion
23 Sep, 2008 - 06:02 AM
Post #12

D.I.C Head
**

Joined: 1 Nov, 2007
Posts: 115


My Contributions
I'm beginning to understand, atleast a little. Thanks for trying to explain.

Can you show me how to convert these files from java.util.Scanner to javax.swing.JOptionPane?

I know I need to import it at the beginning of the main file, but I'm having difficulty with the showInputDialog and showMessageDialog code.

Thanks!
User is offlineProfile CardPM
+Quote Post

2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 04:55AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month