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;
}
Related
So, first off, in my class Film I need to declare various fields including a string array of actors a fixed length (5). My default constructor needs to set these values for now but later I think I'll need the 5 string values to null so I can add actors up to the limit.
I then want to be able to create instances of the class using values passed to a constructor and finally add actors to the string array of a given film - where there's a free spot (and throw an exception when there's not one).
What I have so far:
public class Film {
private String title;
private String[] actors = new String[5]; // can I set the limit here and use this string below?
private double budget;
// default constructor:
public Film() {
title = "Default title";
// This creates a new string though and doesn't limit to 5 :o(
authors = new String[] {"a","b","c","d","e"};
budget = 1.1
}
// constructor which takes values passed in:
public Film(String title, double budget, String[] actors) {
this.title = title;
this.budget = budget;
this.actors = actors;
}
}
In my main programme, I have the following which shows an error on the comma after the budget value and I can't work out why:
public class Main {
Film homeAlone = new Film("Home Alone", 10.9, ("McCauley", "John", "Paul", "George", "Ringo"));
}
And as for the 'adding an actor' method - I don't know where to start. Any help would be greatly appreciated!
Cheers,
Mike
You are initializing the array in this line
private String[] actors = new String[5];
and again in this line
authors = new String[] {"a","b","c","d","e"};
The first statement created an empty array of length 5 and it does restrict it to 5 elements. If you write below statements, it will throw an exception because array created has 5 bins only 0...4 and can hold only 5 elements
private String[] actors = new String[5];
actors[5]="John";
But again when you wrote the second statement you have reinitialized the previous array to 6 elements by passing 6 elements in the constructor itself and it created a new array of length 6 having those 6 elements you passed in the constructor.
Now again if you want to execute statement below it will throw an exception.
authors = new String[] {"a","b","c","d","e"};
authors[6]="f";
More about arrays in java here https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Use a varargs for the actors:
public Film(String title, double budget, String... actors) {
this.title = title;
this.budget = budget;
this.actors = actors;
}
Then you can create a new Film with any number of actors:
Film a = new Film("Foo", 1.1, "Ringo");
Film b = new Film("Bar", 1.1, "Ringo", "John", "Paul");
Delete the default constructor - it serves no useful purpose.
Don’t declare the array for the field; just code String[] actors;
you should instantiate your Film class as following:
Film film = new Film("Movie", 10.00, new String[]{"a", "b", "c","d","e"});
This because you want to pass an array to the Film constructor.
As for adding actors to a movie, you could add a function to the film class which verifies that the that there is a free spot, and if this is the case add it on the free spot.
you must add semicolon ; after budget = 1.1
you have no variable called authors , perhapse you mean actors?
you cannot initialize a string array like
("McCauley", "John", "Paul", "George", "Ringo")
it must be new String[]{"McCauley", "John", "Paul", "George", "Ringo"}
i suggest you use an IDE like eclipse or netbeans, as it can give you a clue to all of these issues and how to fix them
EDIT based on OP question about limiting to 5:
if you want to limit to 5 you can either :
pass each name as a separate argument and populate the array in the
constructor
accept any size array and only populate the first 5
validate by throwing an exception if array of size more than 5 is
passed
I have an Arraylist of String.
private List<String> listGroup = new ArrayList<String>();
One elements of listGroup is
"CyberHacking Tools,CLS,Tim Hemmingway,2,P132303,Tyler Johnson,APP,M,P132304,Patty Henderson,APP,F".
I need to store the first five elements into a project object which has constructor in project class, while looping the rest to store them into Student object with constructors in Student class. The student object only holds 4 parameters and after every four, it will store a new student object. All of these objects will hence be passed into a Student and Project list.
The codes for these objects are written below.
In the Project class:
public Project(int noOfProj, String title, String sch, String superv, int NoOfStudent) {
this.noOfProj = noOfProj;
this.title = title;
this.school = sch;
this.supervisorName = superv;
this.noOfStudent = NoOfStudent;
// this.projIndex = projCode;
}
This is the Project object:
Project p = new Project(title, school, supervisorName, noOfStudents);
I have a project class, student class,FileReader class and JFrame class respectively. What is the best way to go about this?
Thank you.
First thing, your Project constructor seems to have 4 parameters and not 5. Said that,
// considering this as your sample line -
// String line = "CyberHacking Tools,CLS,Tim Hemmingway,2,P132303,Tyler Johnson,APP,M,P132304,Patty Henderson,APP,F"
String[] tuple = line.split(",");
// Get first 4 tuples for Project.
// CyberHacking Tools,CLS,Tim Hemmingway,2
Project project = new Project(tuple[0], tuple[1], tuple[2], tuple[3]);
// Iterate over rest of the tuples for Student.
// P132303,Tyler Johnson,APP,M
// P132304,Patty Henderson,APP,F
for (int i = 4; i < tuple.length; i += 4) {
Student student = new Student(tuple[i], tuple[i + 1], tuple[i + 2], tuple[i + 3]);
// add the student object to List<Student> here.
}
I will assume you want to store the project and student objects for later usage. Here's the approach you can take:
List<Project> personList = new ArrayList<Project>(); //store list of projects
List<Student> listStudent = new ArrayList<Student>(); //store list of students
for (String str : listGroup)
{
String arr[] = str.split(",");
// as student object takes 4 arguments and "noOfStudents" is
// the number of "Student" objects found in the string
int noOfStudents = (arr.length / 4)-1;
Project p = new Project(Integer.parseInt(arr[3]), arr[0], arr[1], arr[2], noOfStudents);
personList.add(p);
for (int i = 4; i < arr.length-4; i += 4)
{
listStudent.add(new Student(arr[i], arr[i+1], arr[i+2], arr[i+3]));
}
}
Note: while creating the objects of Person and Student I've passed parameters arbitrarily assuming the sequence of the strings will be consistent. Hope you can pass the parameters according to your constructor parameter sequence.
My problem is when a user enters text it should have two elements to split when using .split() however with the items it splits how do I put them into different lists so that I can use integer based list to make calculations.
e.g.
a user enters "skyrim , 100" the 'skyrim' entry is a string however with the number (integer) '100' I want to split it removing the comma and add it to a ArrayList for calculations and with other inputs added.
game name(String) , hours(integers) <- template
skyrim , 100
oblivion , 25
GTA V , 50
so the listed items above are user input with 2 arguments separated by a comma, which will be split, then I need to add them to different arraylists.
Scanner input = new Scanner(System.in);
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
String gameEntry = input.nextLine().split(" , ");
allGameData.add(gameEntry);
foreach(object items : allGameData) {
System.out.println(items);
}
so from here I should have:
skyrim , 100 , oblivion, 25, GTAV , 50
How do i put the game names into the game list and the numbers into the hours list?
Well for starters, the class you should be using is ArrayList with a capital L. So you need to change:
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
to this:
ArrayList<String> game = new ArrayList<>();
ArrayList<Integer> hours = new ArrayList<>();
ArrayList<Object> allGameData = new ArrayList<>();
After we have them initialized correctly we add to the ArrayList with #.add so in your case you would add to the game and hours list like:
game.add("some game");
hours.add(10);
When you split your input with input.nextLine().split(" , "); we are expecting a String array to be returned. Currently you are trying to set this to just a String instead of a String array.
while (true){
System.out.println("Enter \"game , hours\" or \"Quit\"");
String line = input.nextLine();
if (line.equals("Quit")) break;
allGameData.add(line);
String[] parsedData = line.split(" , ");
game.add(parsedData[0]);
hours.add(Integer.parseInt(parsedData[1]));
}
You can use Integer.parseInt(). The code you submitted looks pseudo-codey, but this is something like what You're going for:
String gameEntry = input.nextLine();
allGameData.add(gameEntry);
String[] splitGameEntry = input.nextLine().split(" , ");
game.add(splitGameEntry[0]);
hours.add(Integer.parseInt(splitGameEntry[1]));
I don't know exactly what you're trying to accomplish with this code, but you may want to organize the game/hours into a class that holds both values. Your code would then look something like this:
public class GameInfo
{
private String name;
private int hours;
public GameInfo(String name, int hours)
{
this.name = name;
this.hours = hours;
}
[getters/setters]
#Override
public String toString()
{
return name + ": " + hours + " hours played!";
}
}
public class Main
{
public void doSomething()
{
Scanner input = new Scanner(System.in);
List<GameInfo> gameInfo = new ArrayList<>();
String[] gameEntry = input.nextLint().split(" , ");
gameInfo.add(new GameInfo(gameEntry[0], Integer.parseInt(gameEntry[1]));
for(GameInfo gameInfoPiece : gameInfo)
{
System.out.println(gameInfoPiece);
}
}
}
Using this approach, you would be able to add as much information into the GameInfo class as you want. For instance, if you wanted to change hours to expectedHoursToComplete and add actualHoursToComplete, you could easily do that.
You may find it easier if you rethink your approach. Rather than have 3 separate lists why not store it all in a single Map<String,Integer> where the key is the game name and the value is the number of hours.
Your code would look something like the following:
Scanner scan = new Scanner(System.in);
Map<String, Integer> gameHoursMap = new HashMap<>();
String currentValue = scan.nextLine();
// Loop until you meet some criteria to end such as typing q or quit
while(!currentValue.equalsIgnoreCase("q")){
// You would need to handle when the value of currentValue doesn't fit what you would normally be expecting before doing the rest
String[] vals = currentValue.split(",");
// Call trim method on the String incase there is any lingering whitespace
gameHoursMap.put(vals[0].trim(), Integer.valueOf(vals[1].trim()));
currentValue = scan.nextLine();
}
You would obviously need to write some error handling for when the input doesn't fit with what you're expecting but you get the gist.
UPDATE:
If you wanted to have more complicated info stored for each game you could wrap it up in a custom class GameInfo and then have a Map<String,GameInfo> where the key is the name and the value is the GameInfo. This would allow you to retrieve all of the game info for a game just based on the name.
public class GameInfo {
private String name;
private int hoursPlayed;
private int level;
// etc
}
You would then amend the while loop to create the GameInfo object instead of just putting a String and int into the Map
// Create the GameInfo object from the corresponding input supplied by the user
GameInfo game = new GameInfo(vals[0].trim(), Integer.valueOf(vals[1].trim()), Integer.valueOf(vals[2].trim()));
// Put it in the map with the name as the key
gameMap.put(game.getName(), game);
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);
}
I want to add some records from sql query but the output is not correct. Always return the last record.
The correct list is :
John
Nick
Mary
Joe
,but always return Joe.
This is the method to add the elements:
public ArrayList<String[][]> getFiledArrayList()
{
// ArrayList<String[][]> fieldsList = new ArrayList<>();
String[][] tempRow = new String[1][2];
ResultSet result;
String sql = "select id, name_of from field";
result = database.exeQueryStatement(sql);
try
{
while(result.next())
{
tempRow[0][0] = result.getString("id");
// System.out.println(tempRow[0][0]);
tempRow[0][1] = result.getString("name_of");
// System.out.println(tempRow[0][1]);
fieldsList.add(tempRow);
System.out.println(fieldsList.get(0)[0][1]);
}
}
catch (SQLException ex)
{
Logger.getLogger(FieldManage.class.getName()).log(Level.SEVERE, null, ex);
}
return fieldsList;
I put the id and the name_of in a String[1][2] table and I want to show the name_of in a jComboBox. Ι want to make an insert and watch the name_of with id
FieldManage fieldmanage = new FieldManage();
ArrayList<String[][]> listOfField;
listOfField = fieldmanage.getFiledArrayList();
String[] fields = new String[listOfField.size()];
System.out.println(listOfField.get(0)[0][0]);
for (int i=0; i<listOfField.size(); i++)
{
fields[i] = listOfField.get(i)[0][1];
System.out.println(fields[i]);//test print show always joe!
}
jComboFields.setModel(new javax.swing.DefaultComboBoxModel(fields));
This code always return Joe.
Also I want to know if there is better way to match an jcombo element with an id.
When populating fieldsList, you repeatedly add references to the same object (tempRow). When your loop modifies the contents of tempRow, all previously added entries also change (since they're the same object).
Move the following line inside the loop:
String[][] tempRow = new String[1][2];
You are trying to create an array of object values.
Using ArrayList<String[][]> is not the way to do this.
Create a class
public class Person {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
self.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
self.name = name;
}
}
Then in your code....
ArrayList<Person> myPeople = new ArrayList<Person>();
Person p = new Person();
p.setName("mary");
p.setId(1);
myPeople.add(p);
Start from there, your doing it the hard way, and given that you are having problems understanding arrays and object references, learn the language before you start using multidimensional primitive arrays in conjunction with loops and collections.
Move this line:
String[][] tempRow = new String[1][2];
as the first line in your while(result.next()) loop.
What is happening:
if you put tempRow outside loop, in 2nd iterator on loop same array is modified i.e overwritten by next value. At the completion of while loop, your fieldsList contains the last element only at all indexes.
Run your loop 3 times and you'' see Mary as output.