my issue is that after running my code I realized that it's not going to cut it. It currently lists all elements of the studentName (string) arrayList and all elements of the studentGrade (double) arrayList.
The problem is, four grades are to be assigned to each student and each set of four grades must be summed up separately (then I will average them out). If I sum up all elements in the studentGrade arrayList... that's not going to be indicative of each student individually. Where should I go from here? I've been struggling to come up with options.
package arrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> studentName = new ArrayList<String>();
ArrayList<Double> studentGrade = new ArrayList<Double>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String student = scanner.nextLine();
if(student.equals("C"))
{
break;
}
else
{
studentName.add(student);
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++) {
Double grade = Double.parseDouble(scanner.nextLine());
studentGrade.add(grade);
}
System.out.println(studentName);
System.out.print(studentGrade);
}
}
}
It sounds like you are in need of a Student class, which holds a student name and an array of the grades for that student. Then you can create a method in that class that sums up all the grades for that student and call that method as you loop over the List of Students.
Either that or a multi dimensional array where the students are one index and the second dimension is an array of grades for each index. Don't go this route unless it's a school assignment and you haven't learned about classes and OOP, because it's terrible to maintain and read.
Related
I am facing a problem with 2D arrays, and I don't know what is the problem or what does the error means too, I am trying to prompt the user to enter the number of classes, and for each class the number of students, and for each student, the name of each one of them in each class, and I have to append the names of students to a 2D array, but I just enter one student's name and it throws an error.
This is my code:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int classes = 0;
int students = 0;
int classNum;
int student;
System.out.print("Number of classes in the school: "); // Prompt the user to enter the number of classes in the school
classes = input.nextInt();
String[][] studentNamesArr = new String[classes][students];
for (classNum = 1; classNum <= classes; classNum++){
System.out.printf("Enter number of Students in class number %d: ", classNum);
students = input.nextInt();
for (student = 1; student <= students; student++){
System.out.printf("Enter Name for student %d in class number %d: ", student, classNum);
studentNamesArr[classNum][student] = input.next();
}
}
}
and this is the output when I run the code:
Number of classes in the school: 2
Enter number of Students in class number 1: 3
Enter (Name, study Type, Grade) for student 1 in class number 1: Joe
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds
for length 0 at StudentProgress.main(StudentProgress.java:28)
no idea how I can store the names properly in a 2D array.
The ArrayIndexOutOfBoundsException is thrown because you defined a 2d array of size [classesCount][0].
Since each class has a different size, we should initialize classes after the dynamic input was taken from the user.
The code iterates from index 1 and where the array starts from index 0.
Make sure to give meaningful names to the variable (students -> studentsNum/studentsCount and etc').
You can do as follows:
Scanner input = new Scanner(System.in);
System.out.print("Number of classes in the school: "); // Prompt the user to enter the number of classes in the school
int classesCount = input.nextInt();
String[][] studentNamesArr = new String[classesCount][];
for (int classIndex = 0; classIndex < classesCount; classIndex++){
System.out.printf("Enter number of Students in class number %d: ", classIndex+1);
int studentsNum = input.nextInt();
studentNamesArr[classIndex] = new String[studentsNum];
for (int studentIndex = 0; studentIndex < studentsNum; studentIndex++){
System.out.printf("Enter Name for student %d in class number %d: ", studentIndex+1, classIndex+1);
studentNamesArr[classIndex][studentIndex] = input.next();
}
}
System.out.println(Arrays.deepToString(studentNamesArr));
Output:
Number of classes in the school: 2
Enter number of Students in class number 1: 1
Enter Name for student 1 in class number 1: John
Enter number of Students in class number 2: 2
Enter Name for student 1 in class number 2: Wall
Enter Name for student 2 in class number 2: Simba
[[John], [Wall, Simba]]
You need to update your array at the class's index with a new array that can hold the students' names after you asked how many students there are in a class. Also arrays' indices begin at 0.
Here is the updated code:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int classes = 0;
int students = 0;
int classNum;
int student;
System.out.print("Number of classes in the school: "); // Prompt the user to enter the number of classes in the school
classes = input.nextInt();
String[][] studentNamesArr = new String[classes][students]; // At this point "students" is 0
for (classNum = 1; classNum <= classes; classNum++){
System.out.printf("Enter number of Students in class number %d: ", classNum);
students = input.nextInt();
studentNamesArr[classNum] = new String[students]; // Create the Array to store the names
for (student = 0; student < students; student++){ // Indices start with 0
System.out.printf("Enter Name for student %d in class number %d: ", student, classNum);
studentNamesArr[classNum][student-1] = input.next();
}
}
}
The problem in your code is first you set students=0 and that means the length of the outer array is 0 then you again set students=some input number form keyboard but this doesn't affect the length of outer array of studentNamearr which is already 0.You can't achieve this by 2d array because number of students in one class can vary with another class but in 2d array number of elements in array must be equal.
This program will ask the user for students name and grade then displays both. The values that the user inputs are stored in array names & array grade. I use a counter controlled for loop to gather user input into the arrays. What if I wanted to enter multiple grades for each student??
Fairly new to programming, any input or thoughts would be greatly appreciated on how to do so...
public class Five {
public static void main(String[] args) {
int students;
Scanner input = new Scanner(System.in); //created input scanner
System.out.println("How many students are on your roster? If you wish to exit please type 00: ");// Initializing statement for program************
students = input.nextInt();
if(students == 00) { //Exit program****************
System.out.println("Maybe Next Time!!");
System.exit(0);
}
String[] names = new String[students];// Array names*******
String[]grade = new String[students]; //Array grade********
// Use Counter to go through Array**************************
for(int counter =0; counter < students; counter++){
System.out.println("Enter the name of a student: " + (counter +1));
names [counter] = input.next();
System.out.println("Now enter that students grade A, B, C, D OR F: ");
grade [counter] = input.next();
}
input.close();// End Scanner object
//Use For loop for Printing names and grades entered by the user**************
System.out.println("Your students names and grades are as follows: ");
for(int counter =0; counter < students; counter++){
System.out.println("Name: " + names[counter]);
System.out.println("Grade: " + grade[counter]);
}
}
}
You could use a ragged array for the grades to enter more than one
You would need to declare it so here is a way to do that.
String[] names = new String[students];// Array names*******
String[][]grade = new String[names][]; //Array grade********
for(int i=0; i<names[i];i++)
{System.out.println("How many grades will you enter for "+names[i]+"?")
int temp=input.nextInt();
for(int j=0; j<names[i][temp-1];j++){
grad[i][j]=input.next();
}}
You should probably make a Student class and a Grades class and store them as objects. Using a data structure your best choice is a hashmap.
HashMap<String, List<String>> grades = new HashMap<>();
grades.put("Jack", new ArrayList<>());
grades.get("Jack").add("A");
You can find out more about HashMap here
I'm really new to Java and I am having some difficulty with the basics of arrays. Some help would be greatly appreciated :).
I created a program that asks the user to enter values into an array. The program then tells the user how many items are in the array, the even numbers that are in the array, the odd numbers in the array and the average of all the numbers in the array.
My problem is this: At present my program has a set number of values in the array which is 5 items. I want to change this so that the user can determine the amount of items they want in the array, and ask the user to continually add values to the array until they enter 'Q' to quit entering values so that the program can continue.
I do not want to modify my code, just the part where the user determines the amount of items in the array.
This is my code:
//main class
public class Even_number_array {
public static void main(String[] args) {
array_class obj=new array_class();
obj.get_numbers();
obj.set_arraylist();
obj.set_numbers();
obj.get_average_of_array();
}
}
//another class
import java.util.Scanner;
public class array_class {
private int[] arr=new int[5]; //here is where I would like to modify my code so
//that the user can determine amount of items in array
Scanner keyboard=new Scanner(System.in);
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
for (int i=0; i<this.arr.length; i++)
{
this.arr[i] = keyboard.nextInt();
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}
public void set_numbers() //Tells user what even & odd numbers are in array
{
System.out.println();
System.out.println("These even numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if (arr[i]%2==0)
{
System.out.print(arr[i]+" ");
System.out.println();
}
}
System.out.println("These odd numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if ((arr[i]%2)!=0)
{
System.out.print(arr[i]+" ");
}
}
}
public void set_arraylist() //Dispalys all items in array
{
System.out.println("These are the numbers currently in your array: ");
for (int i=0; i<arr.length; i++ )
{
System.out.print(this.arr[i]+ " ");
}
}
public double get_average_of_array() //Gets average of all items in array
{
double sum=0;
double average=0;
System.out.println();
System.out.println("the average is: ");
for (int i=0; i<this.arr.length; i++)
{
sum=sum+arr[i];
average =sum/arr.length;
}
System.out.println(average);
return average;
}
}
Any help would be great!
Try:
public int[] get_numbers() {
System.out.println("Please enter numbers for array :");
int size = keyboard.nextInt();
int[] values = new int[size]; // create a new array with the given size
for (int i = 0; i < size; i++) {
values[i] = keyboard.nextInt();
}
System.out.println("There are "+((values.length))+ " numbers in array");
this.arr = values;
return this.arr;
}
Sorry i don't really get what you are asking but maybe you mean this
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int[] array = new int[scanner.nextInt()];
System.out.println(array.length);
Sorry i'm pretty bad in java only been learning it for 2 months now
ArrayList is the object you want. It has functions that allow you to append values at the end. It's a dynamic array in the sense that you can mutate it at will.
Using an ArrayList instead of arrays would be the easiest way to accomplish exactly what you are trying to do.
Another option is to ask how many numbers the person plans on entering from the start.
If, for some weird reason, you are only trying to use arrays without asking the user how many numbers they want to enter... a third option would be to create a new array (being one size larger than the previous array) each time the user enters another number.
Some guidance for the last piece...
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
//Instead of this for loop, you will want a while loop. Similar to "while (userHasntEnteredQ)"
for (int i=0; i<this.arr.length; i++)
{
//You will want to create a new array here.
// int[] newArray = new int[this.arr.length + 1];
// Then copy the values of this.arr to newArray
// Then place the keyboard.nextInt() into the last spot of newArray
// Then set this.arr to newArray
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}
If you want the user to determine how many items are in the array, add this in to your code:
System.out.println("Enter the amount of items in the array:");
while (keyboard.hasNextInt()) {
int i = keyboard.nextInt();
}
private int[] arr = new int[i];
However, you won't be able to add more items to the array than the user defined without getting an ArrayIndexOutOfBoundsException, so there is a better way to do this that uses something called an ArrayList. With an ArrayList, you don't have to worry about setting the size of the array before using it; it just expands automatically when new items are added unless you explicitly set a size for it. An ArrayList can be of any object, but to make it only for integers, declare it like this:
ArrayList<Integer> arr = new ArrayList<>();
To add items to the ArrayList:
arr.add(item);
To read a value by its index:
arr.get(index);
To get the index of an item:
int index = arr.indexOf(item);
There is much more that you can do with an ArrayList. Read about it here.
For my homework, I had to write a program that prompts the cashier to enter all prices and names, adds them to two arrays lists, calls the method that I implemented, and displays the result and use 0 as the sentinel value. I am having difficulty coming up with a for loop in the method, I believe I have the condition right but I am having trouble with the statements. Any help would be greatly appreciated! Thanks.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
System.out.print("Enter Number of Customers");
double salesAmount;
System.out.print("Enter Sales for First Customers");
salesAmount = in.nextDouble();
while(salesAmount != 0)
{
sales.add(salesAmount);
System.out.println("Enter Name of Customer: ");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales, ArrayList<String> customers)
{
String name = "";
double maxSales;
for (int i = 0; i < sales.size(); i++)
{
sales.size(name.get); <== it keeps saying "cannot find the symbol variable get"
}
return name;
}
Don't use maxSales as the maximum in your loop. Use the count of number of customers. Inside the loop, check if sales.get(i) is greater than your current maxSales, and if it is...
(I will edit this and more if you still need. But this should go a long way.)
There are a couple possible issues here, but I'll stick to answering what I think is the question that you've asked.
In your nameOfBestCustomer method, you'll want to loop from 0 to the end of either of your ArrayLists (as they both should be the same size).
for (int i = 0; i < sales.size(); i++)
{
...
}
Hey, so i have this hw assignment and i have to write a program that allows the user to input students names and grades and give back the higest lowest and average. The only problem is there is a max 50 students in the class(or so the sheet says) and there are only 10 students names and grades on it. How do i get the array to end after the last student?
static final int MAX = 50;
public static void main(String[] args)
{
int index, average;
int highest = 0, student = 1;
Scanner keyboard = new Scanner(System.in);
String [] students = new String[MAX];
int[] grades = new int[MAX];
System.out.println("Please enter the name of the student and their test grade");
System.out.print("Students: ");
for(index=0; index<MAX; index++)
{
students[index] = keyboard.nextLine();
student = student + index;
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
}
System.out.print("Grades: ");
for(index=0; index<student; index++)
grades[index] = keyboard.nextInt();
averageMan(grades, student);
for(index=0; index<student; index++)
if(grades[index] < averageMan(grades, student))
System.out.println(students[index] + " Your test grade was " +
"below the class average. Step it up.");
for(index=0; index<student; index++)
if(grades[index] > highest)
highest = grades[index];
System.out.println("The highest test grade in the class goes to " +
students[highest] + " with a grade of " + grades[highest]);
}
public static int averageMan(int[] g, int s)
{
int index, sum = 0;
int averages;
for(index=0; index<s; index++)
sum = sum + g[index];
averages = sum / s;
return averages;
}
}
Use Collections, not arrays. Their api is a lot more usable.
Read the Collections Trail to get started.
If you want a drop-in replacement for an array, use a List, if you want uniqueness, use a Set.
You could loop round collecting student details until the user enters a specific token that indicates that they have finished entering details.
EDIT Which looks like what you're trying to do..... but continue goes to the next item in the loop. You want to break out don't you?
Initialize the students array with empty strings. Also Initialize the grades array with -1. In your loop for calculating average/highest/lowest, check for empty string and -1.
Try changing
student = student + index;
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
to:
if(students[index]=="Done"))
{
break;
}
student = student + 1;
Then you will quit the entry loop when a student's name is input as "Done" and the variable student will contain the number of students that were input.
1) Hey, why are you doing this?
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
2) you can divide code into smaller methods
3) you can use Collections API as someone suggested.
The easiest solution would be to use a collection class, like java.util.ArrayList instead of an array. If you have to use arrays, maybe you could reallocate the array each time you add a new Student? This page has an example of how to do that - How to resize an array in Java.
Your for loop has three parts, the middle part resolves to a true/false condition. It can be simple, like you have or complex, like this:
for(index=0; index<MAX && !done; index++)
Where done is a boolean that is false until you detect a value that indicates you want to stop then becomes true.
I would use a generic array list http://www.oracle.com/technetwork/articles/javase/generics-136597.html