Can you help, is there something wrong in my code - java

I have a main class and then when I divide each element (id, name, surname, ...) then I should to save it in the list in another class called Student, and there class students. There are errors such as "method Collection.add(String[]) is not applicable". So what is the problem?
public class ProjectWork{
public static void main(String[] args) throws IOException{
Scanner fin = new Scanner(new File("data.txt"));
int i;
String str,name="",surname="",id="";
String [] midterms = new String[3];
while(fin.hasNextLine()){
str = fin.nextLine();
StringTokenizer toks = new StringTokenizer(str,"|");
while(toks.hasMoreTokens()){
id = toks.nextToken();
name = toks.nextToken();
surname = toks.nextToken();
for(i=0;i<3;i++){
midterms[i] = toks.nextToken();
}
}
Student(id,name,surname,midterms);
}
}
public static void Student(String id, String name, String surname, String[] midterms) throws IndexOutOfBoundsException{
private List<String[]> students = new ArrayList<String[]>();
students.add(id);
students.add(name);
students.add(surname);
}
}

Because, see this line:
private List<String[]> students = new ArrayList<String[]>();
It accepts Array of string, where as you are adding only String like this:
students.add(id);
So you are getting that error. Either declare students like this:
private List<String> students = new ArrayList<String>();
Or add "String" array using add method.

You've declared that you collection, students should take String arrays...
List<String[]> students = new ArrayList<String[]>();
But you are trying adding String elements to it, which are not the same thing.
Either change it so it does add String[] arrays...
List<String[]> students = new ArrayList<String[]>();
students.add(new String[]{id,name, surname});
or redecalre it to take String
List<String> students = new ArrayList<String>();
students.add(id);
students.add(name);
students.add(surname);
Based on what I understand your code is trying to do, I think you want the first one.
(ps- Local variables cannot be declared with access modifiers (ie private), you'll want to get rid of that)
Overall, you code doesn't make a lot of sense. You're calling a static method Student, which creates a List, adds some elements to it and the discards all that work when it exist. Is Student suppose to be a class?

You are trying to add String objects to a List, change this because you are not adding three arrays of type String:
private List<String> students = new ArrayList<String>();

You declare the students type as Array of String. So you should add an array to the collection.
To add id, name, surname, You can declare the collection type as String.
ie List<String> students = new ArrayList<String>();
The method should be like this:
public static void Student(String id, String name, String surname, String[] midterms) throws IndexOutOfBoundsException {
//List<String[]> students = new ArrayList<String[]>();
List<String> students = new ArrayList<String>();
students.add(id);
students.add(name);
students.add(surname);
}

Related

Java Cannot initialize ArrayList variables in constructor

I have several different types of ArrayLists.
Each stores split data from a .csv file.
//NOTE: this is for understanding, syntax may not be correct.
ArrayList<String> name = {item1, item2, item3, item4};
ArrayList<String> type = {type1, type2, type3, type4};
ArrayList<Double> price = {price1, price2, price3, price4};
ArrayList<Integer> qty = {qty1, qty2, qty3, qty4};
In my Item class I have a constructor like so,
public Items(String t, String n, Double p, Integer q){
type = t; //type mismatch : cannot convert from String to ArrayList<String>
name = n;//type mismatch : cannot convert from String to ArrayList<String>
price = p;//type mismatch : cannot convert from Double to ArrayList<Double>
qty = q;//type mismatch : cannot convert from Integer to ArrayList<Integer>
}
As you can see, I cant initialize my constructor because of different types. However, in my main method I call each variable as so,
public static void main(String[] args){
ArrayList<Items> itm = new ArrayList<Items>();
Items general = new Items();
//place each item into object itm
for(int i = 0; general.name.size(); i++)
{
itm.add(new Items(general.type.get(i), general.name.get(i), general.price.get(i); general.qty.get(i)));
} //throws no syntax errors
If I put "general.name.get(i)" for example, wouldn't Java see that as a String and not an ArrayList? How do I initialize these variables in my constructor?
EDIT: When I use general.type.get(i); I want that index from ArrayList type to equal t in the constructor. This is the same for n, p, and q.
t = general.type.get(i);
A box for eggs ... is not an egg.
A list of strings ... is not a string.
Meaning: you can't create a list of strings directly from that single string. You can only add a string into a already existing list. Like putting an egg in your egg-box.
You need:
type = new ArrayList<>();
type.add(t);
for example; or shorter using that little helper method:
type = Arrays.asList(t);
And your other code with items is working because general.type.get(i) returns a single String object; and that is exactly what your Item constructor expects - a single string object.
You are trying to initialize an ArrayList as String. If you tell what you really want to achieve, I can edit the code to do so.
Item Class
public class Item {
public static ArrayList<String> type_list = new ArrayList<>();
public static ArrayList<String> name_list = new ArrayList<>();
public static ArrayList<Double> price_list = new ArrayList<>();
public static ArrayList<Integer> qty_list = new ArrayList<>();
public String type;
public String name;
public Double price;
public Integer qty;
public Item (String type, String name, Double price, Integer qty){
this.type = type;
this.name = name;
this.price = price;
this.qty = qty;
}
}
Main Class
public static void main(String args[]){
ArrayList items_list = new ArrayList<>();
Item.type_list.add("type1");
Item.type_list.add("type2");
Item.type_list.add("type3");
Item.type_list.add("type4");
Item.name_list.add("name1");
Item.name_list.add("name2");
Item.name_list.add("name3");
Item.name_list.add("name4");
Item.price_list.add(price1);
Item.price_list.add(price2);
Item.price_list.add(price3);
Item.price_list.add(price4);
Item.qty_list.add(qty1);
Item.qty_list.add(qty2);
Item.qty_list.add(qty3);
Item.qty_list.add(qty4);
for(int i = 0; i < Item.type_list.size(); i++) {
System.out.println(.....);
}
}

How to create new object in a for loop?

I want to create some objects in a program using for loop. The parameters of the objects are accepted from key board. My question is how to create different objects in a for loop. Here is what I have.
import java.io.*;
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
class Course{
Course (String name, String sem, int numOfPre){
this.name = name;
this.sem = sem;
this.numOfPre = numOfPre;
}
String name;
String sem;
int numOfPre;
}
Scanner scanner = new Scanner(System.in);
System.out.print("Input two integers here: ");
String totalCourse = scanner.nextLine();
String[] numOfCourse = totalCourse.split(" ");//[0] num of total course [1] max num per semester
for(int i = 0;i < Integer.parseInt(numOfCourse[0]); i++){
System.out.print("Please input course info here: ");
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
String courseName = infoOfCourse[0];
String courseSem = infoOfCourse[1];
int courseNumOfPre = Integer.parseInt(infoOfCourse[2]);
Course course = new Course(courseName,courseSem,courseNumOfPre);
//How to create different objects?
}
scanner.close();
}
}
You could save the objects you are creating in an array.
Before the for loop:
// create an empty array with the size of the total courses
int numOfCourses = Integer.parseInt(numOfCourse[0]);
Course courses[] = new Course[numOfCourses];
Inside the loop:
courses[i] = new Course(courseName, courseSem, courseNumOfPre);
Collection
The answer by Securo is correct. But rather than an array, it is more flexible and powerful to use a Collection. If you want to keep the objects in the order of their creation, use the List interface, with an ArrayList as the implementation.
Before the loop starts, define an empty List.
List<Course> courses = new ArrayList<>();
If you know the number of courses, pass that number as the initial size of the ArrayList. Helps performance and memory usage a little bit if the ArrayList need not be resized.
List<Course> courses = new ArrayList<>( numberOfCourses );
In your loop, instantiate the objects and add to the List.
Course course = new Course( … );
courses.add( course );

Trying to convert program from array to array list java

I have two classes. At the moment, you can save 99 entries to a .txt file. Obviously I want to expand upon this. It would be good if the following from ExamGradesGUI were an arraylist rather than an array:
String[] firstName = new String[99];
String[] lastName = new String[99];
String[] subjectUnit = new String[99];
double[] examMark = new double[99];
I managed to start off by declaring the array as below (for firstName):
ArrayList<String> firstName = new ArrayList<String>();
Then, I was not sure how to make it work with my get and set methods as obviously they are still in array form. If someone could help I would appreciate it. Thanks
Maybe it should be more OOP to have :
List<Student> students = new ArrayList<Student>();
Class Student{
private String firstName;
private String lastName;
private String subjectUnit;
private double examMark ;
// Generate getters and setters and constructor
}
// So the code to create a new Student in getText():
Student newStudent = new Student (
firstNameTxt.getText() ,
lastNameTxt.getText(),
subjectUnitTxt.getItemAt(subjectUnitTxt.getSelectedIndex()),
Double.parseDouble(examMarkTxt.getText()) );
// add the newStudent to the list
students.add( newStudent );
There is a method List#add(int index,E element)
void add(int index,
E element)
Inserts the specified element at the specified position in this list
(optional operation). Shifts the element currently at that position
(if any) and any subsequent elements to the right (adds one to their
indices).
with this method you can replace
firstName[i] = firstNameTxt.getText();
this with
firstName.add(i,firstNameTxt.getText());
Update
you can replace
public void addRecords(String[] first, String[] last, String[] subject, double[] mark)
with
public void addRecords(List<String> first,List<String> last, List<String> subject,List<double> mark) {
this.firstNameList=first;
this.lastNameList=last;
this.subjectList=subject;
this.marksList=mark;
}

How to create an ArrayList of arrays of Objects in Java?

I was wondering how exactly to create an ArrayList of an array of objects. For example
Object[] objectArray = new Object() // Varying amount of object[]
I would like to add Object[] to an ArrayList as they come in. I have seen that an ArrayList of arrays can be created by the following:
ArrayList<String[]> action = new ArrayList<String[]>();
So I was thinking it would be as simple as:
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
But apparently not.
You create an ArrayList of arrays this way :
ArrayList<Object[]> action = new ArrayList<Object[]>();
Each time you add an Object[] to that list, it must have a fixed length.
If you want variable length arrays inside the ArrayList, I suggest you use ArrayList<ArrayList<Object>>.
Your syntax with objectArray is simply not valid Java syntax.
The type parameter in the generic List class should be the class name and not the name of the variable that references the array:
ArrayList<Object[]> action = new ArrayList<Object[]>();
Two notes:
Try to avoid declaring types to the implementations. Declare action as a List (the interface):
List<Object[]> action = new ArrayList<Object[]>();
It would make life a bit easier if you make the parameter another List instead of an array of Objects:
List<List<?>> action = new ArrayList<List<?>>();
ArrayList<LoadClass[]> sd = new ArrayList<LoadClass[]>();
This works :)
So, you have two questions:
Object[] objectArray = new Object()
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
Change it to:
int MAX_ARRAY = 3;
Object[] objectArray = new Object[MAX_ARRAY];
ArrayList<Object[]> action = new ArrayList<Object[]>();
Now you can add your objectArray to "action":
action.add(objectArray);
It's a easy stuff.
// Class Student with a attribute name
public class Student{
String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public static void main(String[] args) {
// Creating an ArrayList for Students
ArrayList<Student> students = new ArrayList<Student>();
// Creating an Students Objects
Student a1 = new Student("Name1");
Student a2 = new Student("Name2");
Student a3 = new Student("Name3");
// Populating ArrayList<Student>
students.add(a1);
students.add(a2);
students.add(a3);
// For Each to sweeping all objects inside of this ArrayList
for(Student student : students){
System.out.println(student.getName());
}
}
Enjoy!

Add strings to String ArrayLists stored within an ArrayList

I am trying to retrieve some data from two different websites and want to store them in different arraylists for further processing. So in summary, I have 6 String arrayLists and then I have three arraylists to whom I have added these String arrayLists. I have done so to add data to the String arrayLists using a loop (please see code below). It however is not adding data to the String arrayLists in the manner I expected, obviously my logic is wrong. Just a little guidance would be much appreciated. The relevant Snippets of my code are below :
//creating the String type ArrayLists
private static ArrayList<String> m1=new ArrayList<String>();
private static ArrayList<String> re1=new ArrayList<String>();
private static ArrayList<String> ra1=new ArrayList<String>();
private static ArrayList<String> m2=new ArrayList<String>();
private static ArrayList<String> re2=new ArrayList<String>();
private static ArrayList<String> ra2=new ArrayList<String>();
//creating three ArrayLists of ArrayLists
private static ArrayList<ArrayList> arraylistM = new ArrayList<ArrayList>();
private static ArrayList<ArrayList> arraylistRe = new ArrayList<ArrayList>();
private static ArrayList<ArrayList> arraylistRa = new ArrayList<ArrayList>();
public static void main(String[] args) throws Exception
{
URL[] item=new URL[2];
item[0] = new URL("http://www.example111111.html");
item[1] = new URL("http://www.example222222.html");
arraylistM.add(m1);
arraylistM.add(m2);
arraylistRe.add(re1);
arraylistRe.add(re2);
arraylistRa.add(ra1);
arraylistRa.add(ra2);
for(int loop=0;loop<2;loop++)
{
BufferedReader in = new BufferedReader(
new InputStreamReader(
item[loop].openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
String withoutSpeechMarks=inputLine.replaceAll("\"", "");
String[] parts = withoutSpeechMarks.split("<span x=");
for (int i=0;i<parts.length;i++)
{
if (parts[i].contains("1>"))
{
(arraylistM.get(i)).add(parts[i].substring(13, (parts[i].length())-7));
}//get the first string array in arraylistM and add this data to it
if (parts[i].contains("2>"))
{
(arraylistRe.get(i)).add(parts[i].substring(9, (parts[i].length())-10));
}
if (parts[i].contains("3>"))
{
(arraylistRa.get(i)).add(parts[i].substring(7, (parts[i].length())-7));
}
}//end of inner for loop
} //end of while
in.close();
}
for (int i = 0; i < arraylistM.size(); i++)
{
System.out.println(arraylistM.get(i)+"||"+arraylistRe.get(i)+"||"+arraylistRa.get(i) );
}
The way I want it to be is that from the first website, the extracted results should be added to the string arrays m1, re1, ra1 and then from the second website the data should be added to the string arrays m2, re2, ra2. The data IS being added but all together and is not separated as I wish it to be.
From your description, it sounds like you should be using
arrayListM.get(loop).add( ... )
arrayListRe.get(loop).add( ... )
arrayListRa.get(loop).add( ... )
in the first loop instead of
arrayListM.get(i).add( ... )
arrayListRe.get(i).add( ... )
arrayListRa.get(i).add( ... )
Also, you should consider declaring your ArrayLists of ArrayLists as:
ArrayList<ArrayList<String>>
instead of
ArrayList<ArrayList>
It seems that you are facing issue while merging two Arraylist. You can easily join two ArrayList using addAll method.
ArrayList<String> al1=new ArrayList()<String>;
ArrayList<String> al2= new ArrayList()<String>;
al1.addAll(al2);
It would add all the elements of second arraylist to the first arraylist

Categories