Array setting length and storing information - java

This is homework. I'm trying to work with arrays and this is the first project working with them. My book shows all kinds of examples but the way they code the examples doesn't do any justice to what the assignment calls for.
I am trying to write a program that asks a user to enter students into the system. The program first asks how many you will enter then it will prompt you for the first name, last name, and score.
What I am trying to accomplish with this section of code is to ask the user how many students they will enter. The line of code that says
getStudentCount();
is a method that collects that information and then returns studentCount
I tried to code this to where the length of the array is going to be the number the user enters but it's not working so I wanted to ask for guidance. Ideally if this works and the user enters 3 then you will be prompted to enter the information 3 times. If the user enters 0 then the program doesn't ask you anything.
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application.");
int studentCount = 1;
getStudentCount();
studentCount = sc.nextInt();
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
{
Student s = new Student();
String firstName = getString("Enter first name: ");
s.setFirstName(firstName);
String lastName = getString("Enter last name: ");
s.setLastName(lastName);
int score = getScore("Enter score: ");
s.setScore(score);
}
}
Everything I had in the program worked up until I tried to code
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
which tells me there is something wrong with the way I am doing this.
Also the assignment asks that I store the information in the array. I'm not clear on how to call it or I guess store it.... I have another class with setters and getters. Is that enough to store it? How would I call it?
Again this is homework so any guidance is appreciated.
Thanks!

Well that's at least a homework example that shows some work on the part of the askee (and nicely written), so here's some help:
You set the studentCount to 1 and then call getStudentcount(), but never assigns the return value to your variable, hence the variable stays 1 (though you're overwriting it afterwards with sc.nextInt() which is probably not what you want if you already have a nice method for it). The fix is just to assign the return value of your method to the variable [1]
[1] Yes I know I shouldn't answer homework questions completely, but I really saw no way whatsoever to answer that only partially - proposals welcome though :)

My hints:
Look carefully at how you are getting the student count, and where you are putting it. You seem to be getting the count in two different ways, and that is at best redundant, and probably a bug.
Presumably there is a stack trace. Read it!!
The stack trace will tell you what exception was thrown, what its diagnostic message is, where it was thrown, and where in your code it was executing when the problem happened.
If you are having difficulty visualizing what is going on, use your Java IDE's debugger and single step the program.
Based on your follow-up comments, there isn't a stack trace. But if there was one, you should read it :-)

I don't understand your lines
getStudentCount();
studentCount = sc.nextInt();
if getStudentCount() "returns" the number they input (as you describe in your text), seems like you should be doing
int studentCOunt = getStudentCount();

I'm trying not to completely do your homework for you, but take a look at the code below for a glimpse of how to do this:
/* Some Declarations You're Going to Need */
private static Scanner scan = new Scanner(System.in); //Private, only need it in here
public static Student[] students; //Public, access it from any class you may need
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
System.out.print("Amount of students:");
int studentCount = scan.nextInt();
students = new Student[studentCount];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
System.out.print("Enter first name:");
String firstName = scan.next();
students[i].setFirstName(firstName);
System.out.print("Enter last name:");
String lastName = scan.next();
students[i].setLastName(lastName);
System.out.print("Enter score:");
int score = scan.nextInt();
students[i].setScore(score);
}
scan = null; //Done with scanner
}

Related

How to generate multiple "Variables" in a list by Just entering the specific number of "Variables" asked to input

this is my first post here and I'm an aspiring programmer as well, so please when you see that I'm kind of talking nonsense don't go too harsh on me.
I'm having a bit of a problem creating a programme that I had in mind, this programme needs to ask the user for input on how many students are going to be marking, the user will insert a certain amount (example 10) after that is going to ask us to put for each of the 10 students a score in percentages.
what I had in mind was to create a For Loop to generate multiple “Variables” but I'm kind of lost on how I'm going to interact with each and one of them, so if you please could help me try to solve this problem that would be great, and please if there is a better way to do it please try to explain it to me as if you are trying to explain to a child. XD
The most simple way is just to use for loop for writting and for reading. I don't know why you need this but i hope it helps.
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i++)
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\n Procentages are: ");
for (int i=0; i<studenti;i++)
{
System.out.println(array[i]);
}
Best regards!
Blaz
So you definitely need an Array for this. There are several types you could use.
For you use-case the standard Array will do.
If you want to comply to object-oriented style, you should use a Student class. But I will do it with strings for now:
int numberOfStudents = 10;
String[] students = new String[numberOfStudents];
// now you can do:
students[0] = "John";
students[1] = "Michael";
// ...
// print all students
for(String student : students){
System.out.println(student);
}
Another way of doing this is with Lists. They are a bit more performance costly than arrays but are way more convienient to work with as you don't have to know how much entries it will have. Look at this:
import java.util.ArrayList;
ArrayList<String> students = new ArrayList<Students>();
students.add("John");
students.add("Michael");
// ...
// print all students
for(String student : students){
System.out.println(student);
}

I need help figuring out how to copy a person's response 100 times in a row

import java.util.Scanner; // *Has to be outside of brackets!*
public class Lab_1_3_Class_oops {
public static void main(String[] args) {
//I need to request a person's first and last name, then copy it on individual lines after they have entered their input
//Variables
Scanner sc = new Scanner(System.in);
//Requesting a name
System.out.print("Please write your first and last name.\n");
//Allowing a name input
sc.nextLine();
//I get as far as allowing text to be entered, but I can't figure out a way to keep that text in the memory long enough to get it copied 100 times without making the person type it 100 times
}
}
I am not looking for direct answers. I just want to know if what I want is possible with the way I have started and how I would even begin to try something like this.
Get the name input as a String and use a for loop to print it. I hope I wasn't too direct.
You need to declare a variable to hold the user's input. Then, you can use a for loop to do whatever you want any number of times.
String name = sc.nextLine(); // Declare a String variable to hold the value
for(int i = 0; i < 1337; i++) { // Use a for loop
// do something
}
Declare a variable to hold the user's input, then put it in a loop(print it from there)
Thank you all so much! The way I fixed it was by declaring
int num = 1;
and then creating a while loop
while (num <= 100) {
System.out.println(name);
num = num + 1;
}
I really appreciate everyone's help without actually telling me the answer.

Symbol table in Java

I'm trying to write a program for manipulating a symbol table in Java. I've used a linked list data structure as a way to represent my symbol table; the linked list(singly) has a key,value associated to that key, and a pointer to the next point. The linked list also provides to the user the function of inserting a new node to the list. It seems that my implementation for the linked list class is going well, but when I was trying write a main program to test that, I've got some problems. Despite the errors that I managed somehow to handle them with exceptions, there is a logical error in my code. Here is the piece of code that I wrote and the output as well:
import java.util.Scanner;
public class Test_GPA {
public static void main(String[]args){
// create symbol table of grades and values
GPA<String, Double> grades = new GPA<String, Double>();
grades.put("A", 4.00);
grades.put("B", 3.00);
grades.put("C", 2.00);
grades.put("D", 1.00);
grades.put("F", 0.00);
grades.put("A+", 4.33);
grades.put("B+", 3.33);
grades.put("C+", 2.33);
grades.put("A-", 3.67);
grades.put("B-", 2.67);
Scanner input = new Scanner(System.in);
double numb =0; int i=0;
double sum = 0.0;
String grade;
Double value;
System.out.println("Please enter number of courses:");
numb=input.nextInt();
while(i<numb){
System.out.println("Please enter the grade for course"+(i+1)+":");
grade = input.nextLine();
value = grades.get(grade);
try{
sum += Double.valueOf(value);
}catch(Exception e){}
i++;
}
double gpa = sum/numb;
System.out.println("GPA = "+gpa);
The problem is the code always skips the reading of the first entry by the user. For example, if I run this program and enter the number of courses to be 4, the result will be as shown:
Please enter number of courses:
4
Please enter the grade for course1:
Please enter the grade for course2:
A
Please enter the grade for course3:
A
Please enter the grade for course4:
A
GPA = 3.0
I don't know actually where is the mistake that I've made. And of course by missing the reading of the first entry that leads to a wrong computation for the GPA. Please, is there anyone interested in showing me how to fix the error. I've tried almost everything i know and it still doesn't work. just FYI, this is the first time i program in Java. Thank you in advance.
Firstly your implementation of LinkedList is not correct linkedlist is not a key-value type of data structure it just links element to other element. I recommend you to look into HashTable that is better for this kind of usage. What happens in your code is new-line character does not get consumed when you get input with nextInt(). Below code should do the trick
numb = Integer.parseInt(input.nextLine());

Java Scanner doesn't work in Processing

For an assignment I have due, my group and I were asked to code an educational/interactive game, and we decided on a basic maths one.
To get the users answers, we decided to use Java Scanner and put this line of code at the top of all the code we have;
java.util.Scanner
One of the loops that use this is the page with the questions on it, the loop looking something like this;
scoreCount = 0;
for (questions = 0; questions < 5;) {
//get the user's answer
userAnswer[questions] = input.nextInt();
//text box for users answer
if (userAnswer[questions] == compAnswer) {
//put tick next to answer
//add one to score
scoreCount = scoreCount + 1;
} else if (userAnswer[questions] != compAnswer) {
//put cross next to answer
}
//go to next question
questions++ ;
}
I'm working through all the errors that were thrown up and every time i don't have java.util.Scanner commented out Processing throws us the errors unexpected token: and then either class or void, which i don't get, but when java.util.Scanner is commented out, the classes and voids all work and the .input.nextInt() isn't recognised.
I am new to Java programming and Processing, any help at all would be greatly appreciated
EDIT
i think this is the link which lets you see my code, it's called Test;
https://github.com/MeganSime/Week8DataVis
you have to check if scanner has next int (token)
Scanner input = new Scanner(System.in);
.
.
if(input.hasNextInt()) { // or hasNext()
userAnswer[questions] = input.nextInt();
}
You're probably inserting a non int value where the scanner expects that. You should do something like that:
if(input.hasNextInt()) {
userAnswer[questions] = input.nextInt();
} else {
scan.next(); //consume any non-int value like ":"
}

Array initialization error

I am doing java programming practice from a website. I have to display this out put using arrays.
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
This is my source code so far, it is raising error The local variable grades may not have been initialized. How do I recover this? I have to make this program using arrays.
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = Integer.parseInt(in.next());
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
}
}
When you write
int[] grades;
you declare a variable called grades, that can hold a value of type int[]. However, before you can use it you also have to initialize it, eg create the actual data structure. This is done like this:
int[] grades = new int[numStudents];
Note that you need to know the size beforehand when you declare an array, so you will have to move the creation of the array to just before the for loop.
All variables declared in methods have to be assigned a value before you read them to avoid trash values.
Also in java arrays are objects, that means that you have to create an array instance with new and assign it to grades before you can store anything in it.
grades = new int[numStudents];
An array doesn't have a constant memory allocation, therefor you must allocate memory to the new array.
for example
int[] grades = new int [numStudents]
This of course should be written only after you know the value of numStudents
There's not much to add to what Keppil already said, but I'd like to add a little 'why'.
You see, when int[] grades is created, it is nothing but an 'empty pointer', pointing to a random location in memory.
By assigning the return value of 'new int[numGrades]', the value of the pointer points to the location in memory, which has been assigned. This memory is in the exact size of 'size of an integer multiplied by the number of grades', and can be accessed safely.
If this array is dimensioned too small (or not at all), a memory violation exception usually gets triggered, because you're writing memory you have no access to, often causing your program to crash or other undefined behavior.
Please remember: Arrays are different from normal variables.
So yeah, to make it short:
grades = new int[numGrades]; is what you're looking for.
Straight below the line, where you're parsing the the input number of students.
As an additional advice: User input is ALWAYS a source for error.
Make sure to include error handling for invalid output. (For example if some wiseguy decides to input 'John Smith' instead of a grade.
You have to initialise variable before its usage.
Please see one of correct version of your code:
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = in.nextInt();
// this line was added
grades = new int[numStudents];
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
// closing used resources is a good practice
in.close();
}
}

Categories