Storing multiple user input in arrays - java

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

Related

Using 2D Array to manage Students in multiple classes (multiple students can share same class)

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.

Summing up an unknown number of Integers in groups of 4

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.

Java: I made a program that accepts input for an integer array & displays values in a table. Trying to recreate this using a string array. Pls. help,

Java is my first programming language, and I'm still unfamiliar with how arrays work. However, I was able to make this program, which accepts user-input for an integer array; it then outputs indexes and values, to show how arrays store numbers. I would like to recreate this program using a string array, to make a table containing a list of friends.
The .length property also confuses me...
Could someone explain the .length property and help me make the string array program work?
Thank you very much.
Here is the working code for the integer array table program
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
Here is the code for the string array program I'm working on
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
.length property stores number of elements in the array. But elements are starting from 0. So, when .length = 1, then there is only one element in the array, with index 0.
It seems in your String arrays program in the for loop the <= should be changed to <
Like this:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)

eOne Dimensional Array with string input on java. Do not know how to make the array stop taking input until the user enters "alldone"

I am suppose to make a one dimensional array until the user enters "alldone", however i dont know how to make it . This what i have and i know it is wrong .
The instruction are "Design a solution that requests and receives student names and an exam score for each. Use one-dimensional arrays to solve this.
The program should continue to accept names and scores until the user inputs a student whose name is “alldone”.
After the inputs are complete determine which student has the highest score and display that student’s name and score.
Finally sort the list of names and corresponding scores in ascending order."
Code so far:
String name = "";
String highName = "";
int highScore = 0;
while (name != "alldone") {
System.out.println("Enter name of student");
name = input.nextLine();
System.out.println("Enter grade of student.");
int score = input.nextInt();
if (name != "alldone" && score > highScore)
highName = name;
highScore = score;
// System.out.println("Enter name"); name = input.nextLine(); }
// System.out.println(highName + " had the highest score which was "
// + highScore);
}
now i have done this
Scanner in = new Scanner(System.in);
int size= 1;
String[] studentNames= new String[size];
System.out.println("Enter name of student");
String input = in.nextLine();
String name = input;
if (!name.equals("alldone")) {
for (int i = 0; i < size; i++)
studentNames[i]= in.nextLine();
}
else return;
for (int k = 0; k<studentNames.length; k++) {
System.out.println(studentNames[k] + " "); //so it can display names
you should use this instead:
if (!name.equals("alldone"))

Student Array menu

I'm coding a menu to store names into an array, then giving options to add/delete students and search for a particular student as well, but I cant seem to find out how to set the array so that I can use it in other options, cause, for example, my code only allows me to input names when I use option 1, but it doesnt keep these names in the array when I choose option 3 to search for a name within the array, it just shows up as null for every slot in the array.
Another problem I am having is about how I can delete students, obviously it would be really easy if the name is at the end of the array but what if the name is in the middle, how would I be able to delete the name, shift all the other names down one slot so that there are no gaps in the array?
import java.util.Scanner;
public class Lab10Ex2 {
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p=0;p<20;p++){
if(searchName.equals(stringarray[p])){
x=1;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
}
}while(choice!=5);
}
}
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
Delete the int[] stringArray line (you don't refer to it anywhere).
Move the String[] stringarray up, outside the loop.
As to deleting, you either have to code that yourself (move everything past the deleted item up one in the array), or use one of the collection classes provided with Java (instead of a native array), which handle deletion for you.
do{
String[] stringarray = new String[20];
On each iteration of your Do { ... } loop, you're recreating the stringarray variable, thus clearing it. If you move this outside of the loop, your student entries will be maintained.
As for deleting, if you're not required to use an array of strings, I would recommend using an ArrayList. It will allow you to easily remove specific entries without worrying about the other entries. Otherwise, yes, the simplest thing to do would be to move all of the other entries down one slot to avoid gaps
Here is the corrected code:
import java.util.Scanner;
public class Lab10Ex2 {
/**
* #param args
*/
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
String[] stringarray = new String[20];
do{
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
System.out.println();
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p = 0; p < stringarray.length ;p++){
if(searchName.equals(stringarray[p])){
x=1;
break;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
System.out.println();
}
}
}while(choice!=5);
}
}
Things you were doing wrong:
Instantiating the array in the do while loop.
Not breaking out of the loop if a search entity was found in the array.
Use ArrayList if you want to avoid wasting space in arrays after deletion. If you are bound to this with simple arrays, you can do this:
Place null at index from which you deleted.Create a temporary array with same size as the original one with all null values. Copy all the elements from the original array to the temporary one but skip elements that are null. Point the original array to the new array.
AND AVOID HARD CODING ARRAY LENGTHS!

Categories