I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)
i want to create 3 arrays with objects.The two arrays(pin and age) i want to put them on one array named Alltogether.I use from each method to return me an array i dont know if this is right i try it.In the end i want to systemout only the array that has all this.
package worklin1;
public class worklin1{
static int N; //from keyboard i have a class userinput
private String Name; // name
private int age; // age
private int costVehicle; //vehicle
public worklin1(){}
public worklin1(String Name, int Age, int cost, String name) {
Name=name;
Age=age;
costVehicle=cost;
}
// Access methods
public String getName(){
return Name;
}
public int getAge(){
return age;
}
public int getcostVehicle(){
return costVehicle;
}
// Mutator methods
public void setName(String name){
Name=name;
}
public void setSurname(String age){
age=age;
}
public void setcostVehicle(int cost){
costVehicle=cost;
}
public String toString() {
String s=name+" "+age+", "+cost+"\t";
return s;
}
public static void main(String[] args){ //main
int[] pin= new int[N]; // the first array
int[] age=new int[]; // the second array.i dont know why it is false this array maybe i use an object as name for an array thats why its false.
Allmethodtogether[] pin = new Allmethodtogether[N]; // Allmethodotogether is an array.It has the combination of age and the cost.The N is just a number i give from keyboard i dont care about this right now.I just wanted to focus on my problem which is how to combine the two methods(which they give me each one 2 arrays and i will add them in this array name Allmethodtogether).
for (int i = 0; i < 10; i++) { // i want to put in an array all the arrays from the methods so i start the counting from 0 until 10.Until the 10 will be saved the pin and after 10 will be saving the array age
Allmethodtogether[i] = new Vehcost();
Allmethodtogether[i+10] = new AllAge();
} //finished //Now i want to display those arrays and i am trying this .
int y; // i create a variable to save my results from the method
y=worklin1.Vehcost(int[] pin); // i take the result from the method Vehcost
System.out.println("Appear all array"+y ); //i want to appear the array.Did i create and an array with objects?
int k; // i do the same thing as the other
k=worklin1.Allage(int[] age);
System.out.println("Appear all array"+k);
} // end main
public static int Vehcost(int[] pin ) { //starting first method 1
int cost = 0;
for(int i =0; i < pin.length; i++) {
cost += pin[i].getcostVehicle();
pin[i]=getname()+ cost; //i want to save to pin the names and the cost of each one
}
return pin[i]; // i want to return the array pin
}//end method 1
public static int allAge(int[] age ) { //second method
if(getage() >18 ){ //if age is >18 only then will going to save on the array
for(int i =0; i < age.length; i++) {
age += age[i].getage();
}
}
return age; // i want to return the array age
}// end method 2
}
The program is supposed to assign random values to the Student objects in the studentArr array.
Right now it is only printing out null values. Ive tried several different print methods.
I'm pretty sure its something wrong with either my method that is supposed to fill out each student object's attributes, or with my print statement.
import java.util.*;
public class Lab6Excercise
{
String[] first={"Rick","Morty","Moriarty","Samus","Promethius","Geiger","Moriarti","Bob","Taco",
"Asparagus","Shoes","Potato","Dirty","Dan","Spongebob","Space","Nova","Illadin","Orange","Electron"};
String[] last={"PoopyButthole","Red","Mantis","Toboggan","Oak","Elm","Dumbledore","Potter","Spice","Toothbrush","Argon",
"Blitz","LazerWolf","Mc-BigMac","King","Queen","Spork","Petrolium","Apple","Trash"};
//no syntax errors if set to static, but prints out null for everything.
//problem here or in calling array to print?
public static Student[] studentArr= new Student[20];
public Lab6Excercise(){
initializeArray();
}
public void initializeArray(){
for(int i=0; i>20; i++){
//this one seems correct but it cant find the symbol method- setStudentID etc. methods
// online it said to try (Student)studentArr.setStudentID(id())
//which explicitely casts it
//seems to work
//http://stackoverflow.com/questions/29328569/setting-values-to-an-array-of-objects
studentArr[i]= new Student();
studentArr[i].setStudentID(id());
studentArr[i].setFirstName(First());
studentArr[i].setLastName(Last());
studentArr[i].setGrade(Grades());
//other way?probably wrong
//studentArr[i]= new Student(studentArr.id(),
//studentArr.First(),
//studentArr.Last(),
//studentArr.Grades());
}
}
public Student[] getStudentArr(){
return studentArr;
}
//do i even need this?
//public Lab6Excercise getLab(){
// return lab;
//}
public static void main(String[] args){
//randomly generate double grade, student id;
//create 2 arrays, first name, last name. pull randomly for name generation
//necessary? how do i
Lab6Excercise lab= new Lab6Excercise();
//prints out hash or something
//System.out.println(lab.studentArr.toString());
//prints out nulls
// System.out.println(Arrays.deepToString(studentArr));
for(int i=0; i<studentArr.length; i++){
System.out.println(studentArr[i]);
}
}
public int id(){
int ID=1+(int)(Math.random()*((100-1)+1));
return ID;
}
public String First(){
Random random= new Random();
int index= random.nextInt(first.length);
return first[index];
}
public String Last(){
Random random= new Random();
int index= random.nextInt(last.length);
return last[index];
}
public double Grades(){
double grade=0+(double)(Math.random()*((4-1)+1));
return grade;
}
}
and the object class
import java.util.Random;
public class Student
{
private int studentID;
private String firstName;
private String lastName;
private double grade;
// no-argument constructor calls other constructor with default values
public Student()
{
this( 0, "", "", 0.0 ); // call four-argument constructor
} // end no-argument Student constructor
// initialize a record
public Student( int id, String first, String last, double grade )
{
setStudentID( id );
setFirstName( first );
setLastName( last );
setGrade( grade );
} // end four-argument Student constructor
// set student ID number
public void setStudentID( int id )
{
studentID = id;
} // end method setStudentID
// get student ID number
public int getStudentID()
{
return studentID;
} // end method getStudentID
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set grade
public void setGrade( double gradeValue )
{
grade = gradeValue;
} // end method setGrade
// get grade
public double getGrade()
{
return grade;
} // end method getGrade
public static int getRandom(int[] array){
int rnd= new Random().nextInt(array.length);
return array[rnd];
}
public String toString(){
return "First name: "+firstName + "Last name: " + lastName+ "ID: "+ studentID+ "Grade: " + grade+"\n";
}
}
You never initialize your array, because your for loop indexing is wrong.
for (int i = 0; i > 20; i++)
This says: for i starting at 0, run the following code if i is greater than 20, incrementing the value of i by 1 each time. Since i starts out already being less than 20, it is never greater than 20, and the code never runs. Instead, do the following, making your run-condition i less than 20:
for (int i = 0; i < 20; i++)
Or, better yet:
for (int i = 0; i < studentArr.length; i++)
For more details on the syntax of the for statement, check out the Java documentation.
It's a simple error in your for loop in the initialize array method. The statement: i >20 is the condition under which the loop will execute. But if i starts as 0 it will never be 20 and the loop will never execute. Just change the condition (which is i >20 right now) to i < 20 and it will work. :)
**this is part of the class i created
class Student{
private String name;
private float avGrade;
private float outstandingGrade = 82.0f;
public Student() { }
public Student(String Name, float avg) {
name = Name;
avGrade = avg;
}
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
}
and this is the main and another method in it :
public static void main(String[] args) {
Student[][] school = CreateStudentMat();
school[0][0].setName("Student");
}
public static Student[][] CreateStudentMat(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter number of classes in school: ");
int NumClasses = input.nextInt();
Student[][] matrix = new Student[NumClasses][];
for(int i = 0; i<matrix.length; i++){
System.out.println("Please enter number of students in class " +(i+1));
matrix[i] = new Student[input.nextInt()];
}
return matrix;
}
when i am trying to change name of the object at [0][0]
with school[0][0].setName("Student");
i get an error
Exception in thread "main" java.lang.NullPointerException
at Homework3.main(Homework3.java:13)
what i did wrong here?
you are instantiating the two dimensional array with matrix = new Student[NumClasses][]
you are instantiating the N one dimensional arrays with matrix[i] = new Student[input.nextInt()]
you are NOT instantiating every single student with matrix[i][j] = new Student()
Hence the two dimensional array is correctly created but every student reference is still null since you are not instantiating any.
There are no student objects. you never called new Student() anywhere. Since array does not have any object, you can't call methods on nulls.
Maybe the problem exist at:
Student[][] matrix = new Student[NumClasses][];
try to initialize the size of the second dimension of your array.
I am having a problem in this code. what i am trying to do is read a file and store a studentID and score into an array of scores into the scores property of a student object, but I keep getting the last scores only when I print. Here is the code. can you tell me if my setter property is a correct way of assigning an array in the student class? the problem is the last line of the score file is stored in every array even though when I debug it I see the score array being passed and the studentID array works fine.
import lab6.*;//importing the necessary classes
public class Main
{
public static void main(String[] args)
{
Student lab6 [] = new Student[40];
//Populate the student array
lab6 = Util.readFile("studentScores.txt", lab6);
lab6[4].printStudent();
}
}
The student class------------------------------------
package lab6;
public class Student
{
private int SID;
private int scores[] = new int[5];
//write public get and set methods for SID and scores
public int getSID()
{
return SID;
}
public void setSID(int SID)
{
this.SID = SID;
}
public int[] getScores()
{
return scores;
}
public void setScores(int scores[])
{
this.scores = scores;
}
//add methods to print values of instance variables.
public void printStudent()
{
System.out.print(SID);
System.out.printf("\t");
for(int i = 0; i < scores.length; i++)
{
System.out.printf("%d\t", scores[i]);
}
}
}
the util class --------------------------------------------------------------------
import java.io.*;
import java.util.StringTokenizer;
//Reads the file and builds student array.
//Open the file using FileReader Object.
//In a loop read a line using readLine method.
//Tokenize each line using StringTokenizer Object
//Each token is converted from String to Integer using parseInt method
//Value is then saved in the right property of Student Object.
public class Util
{
public static Student [] readFile(String filename, Student [] stu)
{
try {
String line[] = new String[40];//one line of the file to be stored in here
StringTokenizer stringToken;
int studentID;//for storing the student id
int[] studentScoreArray = new int[5];//for storing the student score
FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
int i = 0;
buff.readLine();//used this to skip the first line
while (!eof) //operation of one line
{
line[i] = buff.readLine();
if (line[i] == null)
eof = true;
else //tokenize and store
{
stringToken = new StringTokenizer(line[i]);
String tokenID = stringToken.nextToken().toString();//for storing the student id
studentID = Integer.parseInt(tokenID);
stu[i] = new Student();//creating student objects
stu[i].setSID(studentID);//stored in student object
//now storing the score-------------------------------------------------
int quizNumberCounter = 0;
while (stringToken.hasMoreTokens())
{
String tokens = stringToken.nextToken().toString();
studentScoreArray[quizNumberCounter] = Integer.parseInt(tokens);//converting and storing the scores in an array
quizNumberCounter++;//array progression
}
stu[i].setScores(studentScoreArray);//setting the score(passing it as an array)
//-----------------------------------------------------------------------
}
i++;
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
return stu;
}
/*
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
//How to convert a String to an Integer
int x = Integer.parseInt(String) ;*/
}
Sample file Structure -------------------------------------------------------
4532 011 017 081 032 077
The issue lies within the line
int[] studentScoreArray = new int[5];
You'll have to move this one inside your student loop and initialize the array per student. Otherwise you are reusing the same array (i.e. memory) for all students and you are overwriting scores over and over again.
// int[] studentScoreArray = new int[5]; // <= line removed here!!!
...
while (!eof) //operation of one line
{
line[i] = buff.readLine();
if (line[i] == null)
eof = true;
else //tokenize and store
{
int[] studentScoreArray = new int[5]; // <= line moved over to here!!!
...
}
}
I havent tested the code with my suggestion, but take a look at:
int[] studentScoreArray = new int[5];
You create this once and once only for the whole file.
A simple and easy fix is to do it for every new line read instead.
like this :
int[] studentScoreArray = new int[5];
int quizNumberCounter = 0;
while(..) { ...}
One reason you may only being seeing one line of results is that you are only printing one line of results:
lab6[4].printStudent();
You will need to change this to loop through the array if you want to see all the results:
foreach (Student student : lab6)
{
student.printStudent();
}
On a side note, your array should probably be called something like students instead of lab6. Also it is idiomatic in java to declare arrays using Type[] identifier rather than Type identifier [].
DISCLAIMER: There may be other stuff wrong, I didn't read all the hundreds of lines posted!