Adding User Values to Two-Dimensional Arrays - java

I'm trying to create a program called Student Grades, which simulates a grade book for a class with 15 students who each have four test scores. I must use a two-dimensional array to store my data. I need to format my data like "Jeremy Folson, 85, 99, 33, 44". I am having trouble specifically with adding the different students to my array and displaying it properly. I understand that my adding function does not work because will add the same data 15 times. Can someone please explain how to make my code perform the desired task?
// Declare two-dimensional array
Object [][] grades = new Object [15][5];
private void btnAddActionPerformed(java.awt.event.ActionEvent
evt) {
//Clear output area
txtaDisplay.setText(null);
// Declare variables
String firstName, lastName, name;
int test1, test2, test3, test4;
firstName = txtFirstName.getText();
lastName = txtLastName.getText();
name = firstName + " " + lastName;
test1 = Integer.parseInt(txtTest1.getText());
test2 = Integer.parseInt(txtTest2.getText());
test3 = Integer.parseInt(txtTest3.getText());
test4 = Integer.parseInt(txtTest4.getText());
for(int i = 0; i < 15 ; i++){
grades[i][0] = name;
grades[i][1] = test1;
grades[i][2] = test2;
grades[i][3] = test3;
grades[i][4] = test4;
}
}
public void displayArray() {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < 15; row++) {
for( int col=0; col < 5; col++) {
sb.append(String.valueOf(grades[row][col]));
sb.append(", ");
}
sb.append("\n");
}
txtaDisplay.append(sb.toString());
}

First, your data structure conststing only of Object should be improved. A first draft would be:
class StudentEntry
{
String name;
Integer[] grade = new Integer[4];
}
List<StudentEntry> gradBook = new ArrayList<>();
Your main question was why the same combination was entered 15 times. This is due to the aspect that you only read once the input to firstName, ... and then assigned it in the for-loop to every row.
As we don't see when btnAddActionPerformed is called two possibilities:
a. Called each time a student is entered: Just create a new StudentEntry and add it to the gradBook (or if you stay with arrays: keep a counter how many students have already been added, e.g. a static int).
b. Called only when all student records have been entered: use a for-loop and read the next student data inside the loop:
for (int i = 0; i < 15 ; i++) {
StudentEntry student = new StudentEntry();
student.name = txtFirstName.getText() + " " + txtLastName.getText();
...
studentBook.add(student);
}

Related

How to access array from constructor

I just started with Java a few weeks ago and today I've tried to write a program which is able to calculate the average IQ of numbers the user can input. I've written two classes, IQ and IQTester (IQTester = Main only). Now my problem is, whenever I want to calculate something in method compute() (e.g. the average of the array) the whole array is empty. Does anybody know how I can "pass" the array from the constructor to the method compute()?
package IQProgramm;
public class IQ {
private int values[] = new int[10];
private double average;
public IQ(String numbers) {
this.values = values;
String[] values = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < values.length; ++i) {
System.out.print(values[i] + " ");
}
System.out.println("\n");
}
public void compute() {
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}
}
}
package IQProgramm;
import java.util.Scanner;
public class IQTester {
public static void main(String[] args) {
Scanner readIQ = new Scanner(System.in);
System.out.println("Please enter your numbers: ");
String numbers = readIQ.nextLine();
IQ iq = new IQ(numbers);
iq.compute();
}
}
You have 2 different arrays named values, that's why it doesn't work well.
The first defined here String[] values = numbers.split(";"); is visible only in the constructor. If you want to set the value of the one that is available in the rest of the IQ class (private int values[] = new int[10];), you need to edit this one by using
this.values[i] = Integer.parseInt(values[i])
this refers to the variable values of the class IQ.
It is a good practice not to have 2 values with same name. You can change String[] values name to valuesStr for example.
Constructor with the fix:
public IQ(String numbers) {
String[] valuesStr = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < valuesStr.length; ++i) {
this.values[i] = Integer.parseInt(valueStr[i])
System.println(this.values[i]+" ");
}
System.out.println("\n");
}

How can I check whether a value from one array exists in another array?

I have 3 arrays. One counts population, one sorts the population using arrays.sort and the other one stores strings. I want to essentially sort the strings from least to highest. Knowing that the value of where one population is stored is the same as where one string is stored i tried to match the sorted values to the population like this, it it seems to output the strings in the order that I wrote them. Where did I go wrong?
import java.util.Arrays;
public class test {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int Lvalue = 0;
int max = 0;
int min = 0;
int Svalue = 0;
System.out.println("How many countries will be entered");
int num = input.nextInt();
String[] country = new String[num];
int[] population = new int[num];
int[] popsort = new int[num];
String[] capital = new String[num];
for(int i = 0; i < num; i++)
{
System.out.println("Please enter the name of the country");
country[i] = input.next();
System.out.println("Please enter the country population");
population[i] = input.nextInt();
popsort[i] = population[i];
System.out.println("Please enter the country capital");
capital[i] = input.next();
}
for (int i = 0; i < num; i++)
{
if (population[i] > max)
{
max = population[i];
Lvalue = i;
}
}
for (int i = 0; i < num; i++)
{
if (population[i] < max)
{
min = population[i];
Svalue = i;
}
}
System.out.println("The country with largest pop is : " + country[Lvalue] + " ");
System.out.println("The country with smallest pop is : " + country[Svalue] + " ");
Arrays.sort(popsort);
for(int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
if (popsort[j] == population[i])
{
System.out.println(country[i]);
}
}
}
}
}
You can iterate through both arrays and do a comparison, you can use Arrays.binarySearch(), you can convert the array to a List with Arrays.asList() and use contains() on the list, etc. Also careful, you are doing something strange here: if (population[i] < max). That should compare with min, I think.
Instead of storing related information in separate variables, make a class and store information in the same object. Then write a comparator that can sort for you on the basis of the population count. This will also optimize your code.
Eg
class Country {
String name;
int population;
...more fields.
}
you can sort your array using comparator like:
List<Country> countries; // let say you stored all countries in a list or array
Arrays.sort(countries,(country1,country2)->{
return country1.getPopulation() - country2.getPopulation();
}

How to retain an object in an array of objects in Java

I'm not sure how to ask this question. I have to write a program that has 2 classes: one store the data and one call to display the data. The data is Student's name and the names of his/her 4 courses. But I have to put this in a loop for the user to input at least 3 records. If the user doesn't enter a student's name (or name = blank) get out of the loop and display the info entered.
Example:
John Doe MATH 101 ENGL 101 READ 101 COMP 101
Jane Doe PHYS 101 CHEM 101 PSYC 101 ACCT 101
Mary Doe PHED 101 HIST 101 CALC 101 POLS 101
What I'm trying to do is make each of the students' record an object and store those 3 objects in an array of objects then display it.
Below is my code:
import java.util.Scanner;
public class UserInterface {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner(System.in);
//Create an object from Business class
Business b = new Business();
//Declare variables
final int NUMBER_OF_COURSES = 4;
String[] coursesName = new String[4];
Business[] businessArray = new Business[3]; //Declare a array of objects
for (int counter = 0; counter < businessArray.length; counter++) {
//Prompt user to input name
System.out.println("Enter student's name: ");
b.setName(input.nextLine());
for (int i = 0; i < NUMBER_OF_COURSES; i++) {
System.out.println("Enter " + b.getName() + "'s course number " + (i + 1));
coursesName[i] = input.nextLine();
}//end of for(i)-loop
b.setCourses(coursesName);
businessArray[counter] = b;
System.out.println(businessArray[counter]); //Here it display correctly for each round
}//End of for(counter)-loop
for (int pa = 0; pa < businessArray.length; pa++)
System.out.println(businessArray[pa]); //but here it displays 3 records of the last entry
//so my question is how do I retain each entry in its own object and
//adds it to the array of objects?
//I know that b gets overwrite by the last data entered because
//it is just a pointer to that object.
input.close();
}//End of main method
}//End of class UserInterface
The other class:
public class Business {
//Declare variables
private String name;
private String[] courses = new String[4];
//Default Constructor
public Business(){
}
//getter for student's name
public String getName() {
return name;
}
//setter for student's name
public void setName(String name) {
this.name = name;
}
//getter for courses' name
public String[] getCourses() {
return courses;
}
//setter for courses' name
public void setCourses(String[] courses) {
this.courses = courses;
}
}//End of class Business
I know my codes are not good. But I'm required to have getters and setters for each variable in this Business class.
Move your creation of the Business object into the for loop:
for (int counter = 0; counter < businessArray.length; counter++) {
Business b = new Business();
// ...
}
Right now, every entry in the array points to the same object, so you're overwriting the values in it repeatedly. Moving the creation into the loop means you'll have a different object for each slot of the array.
String retainCourse(int pointer){
return this.courses[pointer];
}
Add this function to your business class.
You should overwrite the .toString() method of the class to get the expected result.
In a for loop it is a better practice to get the current object and set it as a temporary variable casted to the exact class! Business current = (Business) businesses[i];

String [][] Output issues

I am trying to write a program that i need to output a 2 dimensional array for a list of first and last names entered by the user. When I try running the program there is no errors, but it gives me this for output:
[[Ljava.lang.String;#b8f82d, [Ljava.lang.String;#1ad77a7,
[Ljava.lang.String;#18aaa1e, [Ljava.lang.String;#a6aeed,
[Ljava.lang.String;#126804e, [Ljava.lang.String;#b1b4c3,
[Ljava.lang.String;#d2906a, [Ljava.lang.String;#72ffb,
[Ljava.lang.String;#1df38fd, [Ljava.lang.String;#16a786,
[Ljava.lang.String;#1507fb2, [Ljava.lang.String;#1efb836,
[Ljava.lang.String;#126e85f, [Ljava.lang.String;#161f10f,
[Ljava.lang.String;#1193779, [Ljava.lang.String;#8916a2,
[Ljava.lang.String;#2ce908, [Ljava.lang.String;#77158a,
[Ljava.lang.String;#27391d, [Ljava.lang.String;#116ab4e,
[Ljava.lang.String;#148aa23, [Ljava.lang.String;#199f91c,
[Ljava.lang.String;#1b1aa65, [Ljava.lang.String;#129f3b5,
[Ljava.lang.String;#13f3045, [Ljava.lang.String;#17a29a1,
[Ljava.lang.String;#1434234, [Ljava.lang.String;#af8358,
[Ljava.lang.String;#d80be3, [Ljava.lang.String;#1f4689e,
[Ljava.lang.String;#1006d75, [Ljava.lang.String;#1125127,
[Ljava.lang.String;#18dfef8, [Ljava.lang.String;#15e83f9,
[Ljava.lang.String;#2a5330]
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code:
package assignment_6_1;
import java.util.Scanner;
import java.util.Arrays;
public class Assignment_6_1 {
public static void main(String[] args) {
//Create a Scanner
Scanner input = new Scanner(System.in);
//Create int & string []
String[][]firstAndLastNames = new String[36][2];
int[]heightOfPerson = new int[36];
//Gather list of names and heights
for(int i=0; i<heightOfPerson.length; i++)
{
//Get first name
System.out.println("Enter Your First Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[1][i] = input.next();
//Get last name
System.out.println("Enter Your Last Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[2][i] = input.next();
//Get height in inches
System.out.println("Enter your height (Iches) " + "Passenger #" + i+1 + ": ");
heightOfPerson[i] = input.nextInt();
if(firstAndLastNames[36][2] != null){
System.out.println(Arrays.deepToString(firstAndLastNames));
break;}
}
}
}
I then have to output the height of the person but I have not gotten that far yet.
Don't use Arrays.toString(array). Use Arrays.deepToString(array). It will print multi-dimensional arrays.
String[][] array = new String[][] {
{ "Apple", "Pear", "Fruit" },
{ "Pi", "Rho", "Omega" },
{ "Jack", "Jill", "Joe" }
};
System.out.println(Arrays.deepToString(array));
//Prints: [[Apple, Pear, Fruit], [Pi, Rho, Omega], [Jack, Jill, Joe]]
Maybe you should not do
for(int i=0; i>35; i++)
but rather
for(int i=0; i<35; i++)
You are stringifying the outer array, but the inner arrays are not handled. What you need to do is to build the output by iterating over the outer array.
This should help:
for (String[] firstAndLastName : firstAndLastNames) {
System.out.println(firstAndLastName[0] + ", " + firstAndLastName[1]);
}
Alternatively you can store the user details in a User object. Then, if you define a toString method on that object thhe original Arrays.toString call will produce more legible output.
class User {
private String firstName, lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
...
public String toString() {
return firstName + ", " + lastName;
}
}
Also, as nielsen points out your for loop has the wrong loop test on it. You have an empty array at the moment so you need to address that as well.
Answer by matthew is perfect but if we do small change in concat operation then it will become more fluent for eg.
public static void main(String...args) {
String[][] firstAndLastName = {
{"Bob","Martin"},
{"Martin","Fowler"}
};
for(String[] name : firstAndLastName) {
System.out.println(toString(name));
}
}
private static String toString(String[] a) {
int iMax = a.length - 1;
StringBuilder b = new StringBuilder();
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.toString();
b.append(", ");
}
}
You are trying to store the last name in a place that does not exist in your array!
You are declaring your array like this:
String[][]firstAndLastNames = new String[35][1];
This means you have 35 rows, and 1 column. Arrays start at index zero. Not one.
When you are trying to store your last names:
firstAndLastNames[i][1] = input.next();
You are not calling the correct column index. Change the array delcaration line line to this:
String[][]firstAndLastNames = new String[35][2]; //now we have 2 columns
Once you store the data correctly, you need to iterate through the array to properly display your data.
try the following code:
public static void main(String[] args) {
String[][] array = new String [3][2]; //Notice how the column declaration is now '2'. This means available indexes are 0 and 1.
Scanner scn = new Scanner (System.in);
for (int i = 0; i < array.length; i++) {
System.out.println ("Enter data " + i + ")");
array[i][0] = scn.nextLine();
}
array[0][1] = "1"; //Understand why this works now?
array[1][1] = "2";
array[2][1] = "3";
for (int i = 0; i < array.length; i++) {
for (int k = 0; k < 2; k++) {
System.out.println((array[i][k]));
}
}
}

Java: creating an array inside of an object class?

I'm attempting to save an x amount of integers inside of an object class. I'm trying it via an array but am not sure if this is possible and as of now eclipse is giving me two errors. One asking me to insert an Assignment operator inside of my Gerbil() class and another saying that I can't make a static reference to to the non-static field food. The result I'm looking for is food 1 = first input; food 2 = second input; until it hits the total amount of food.
Here's my code so far:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public int[] food;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[]; // I'm not sure what I should put here. This is where I want to store
} // the different integers I get from the for loop based on the
// total number of foods entered. So if totalFoods is 3, there should
// be 3 integers saved inside of the object class based on what's typed
// inside of the for-loop. Or if totalFoods = 5, then 5 integers.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil();
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
food[j] = keyboard.nextInt();
}
}
}
}
You need to pass the number of food in the Gerbil constructor :
public Gerbil(int totalFood) {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[] = new int[totalFood];
}
And then in the loop will look like this :
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(totalOfFood);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
GerbilArray[i].food[j] = keyboard.nextInt();
}
}
Or something like that should do it.

Categories