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 );
Related
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.
I am trying to figure out how to use a delimiter to begin the construction of a new object from a text file source.
An example of the txt data that I am using:
"1|Fred|Fish|fredfish#gamer.net|Ithroeann:2|Laurie|Nash|laurieeenash#gmail.com|Mazzzap:"
This is what I have so far to create the first object in the array, but I am wondering how to use the ":" as the second delimiter to build the second object.
I am thinking about using a loop to automate this process.
public class PlayerReader {
public static void main(String[] args) {
Scanner input = new Scanner(new File("commandline.txt"));
input.useDelimiter("|");
Player[] players = new Player[0];
while (input.hasNext()) {
String id = input.next();
String firstName = input.next();
String lastName = input.next();
String emailAddress = input.next();
String gamerTag = input.next();
Player newPlayer = new Player(id, firstName, lastName, emailAddress, gamerTag);
players = addPlayer(players, newPlayer);
}
}
}
I think you are asking about how to deal with the fact that your file has two delimiters -> | separating fields and : separating objects that contain fields.
It should be straightforward. Try following:
Read the entire file content in string.
String content = new String(Files.readAllBytes(Paths.get("commandline.txt")));
Separate the objects delimited by :
String[] objects = content.split(":");
Create a new empty list of your objects - players:
List<Player> players = new ArrayList<Player>();
Convert each object into player by using your business mapping and add each player thus obtained to the above list.
for (String object : objects) {
String[] fields = object.split("|");
player.add(new Player(fields[0], fields[1], ...);
}
I'm learning arraylists, I'm unsure of how to read in from file and add it to a list as I am much more used to arrays, are they alike?
I'm also getting many errors when I am trying to instantiate the class object 'film' but never mind about it.
How am I able to get load my file method working? To me it looks right I think I just need a strangers pov.
Also getting an error when trying to find the file symbol. If there is any specific readings I should do for array lists could you please link me or explain best you can.
I'm very new to both coding and stack overflow so if you could dumb anything down and please be patient if I don't understand anything thanks.
import java.util.*;
public class CinemaDriver {
film[] Film;
public static void main(String[] args) {
Film = new film[100];
ArrayList <Film> list = new ArrayList<Film> ();
}
public void readFromFile() {
File f = new file("file.txt");
Scanner infile = new Scanner(f);
int x = infile.nextInt();
for(int i = 0; i < x ; i++) {
String title = infile.nextLine();
String genre = infile.nextLine();
int screenings = infile.nextInt();
int attendance = infile.nextInt();
file.nextLine();
list.add(title,genre,screenings,name);
}
infile.close();
}
public void displayAll() {
for (film f : list ){
System.out.println(f +"/ \n");
}
}
}
Your ArrayList keeps Film objects as defined here:
ArrayList <Film> list = new ArrayList<Film> ();
But you are trying to insert several different objects or values (Strings, ints, etc...) instead of a Film object
list.add(title,genre,screenings,name);
What you should do is something like this:
Option 1:
list.add(new Film(title,genre,screenings,name));
Option2:
Film f = new Film();
f.setTitle(title);
f.setGenre(genre);
f.setScreenings(screenings);
f.setName(name);
list.add(f);
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 created arrays for strings and integers I want to use in my program and I want to use them instead of using
(name.equals "barry"||"matty"
for example.
I want to know how to write the if statement to check the user input against the strings in the array.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"};
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry ")|| name.equals("matty" ) || name.equals("olly")||name.equals("joey"))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
int [] floor = {0,1,2,3,4,5,6,7};
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
I think you're just looking for List.contains - but that requires a List rather than an array, of course. There are two obvious options here.
Firstly, you could use a List<String> to start with:
List<String> names = new ArrayList<>();
names.add("barry");
names.add("matty");
names.add("olly");
names.add("joey");
...
if (names.contains(name))
{
...
}
Alternatively, you could use Arrays.asList to create a view:
String[] names = {"barry", "matty", "olly", "joey"};
List<String> namesList = Arrays.asList(names);
...
if (namesList.contains(name))
{
}
As a third option, if you put make your names array sorted (either by hand or by calling Arrays.sort) you could use Arrays.binarySearch to try to find the name entered by the user:
String[] names = {"barry", "matty", "olly", "joey"};
Arrays.sort(names);
...
if (Arrays.binarySearch(names, name) >= 0)
{
...
}
Arrays are very low-level structures that don't provide any method. You'd better use collections instead, which have a contains() method:
Set<String> names = new HashSet<>(Arrays.asList(new String[] {"barry", "matty", "olly","joey"}));
if (names.contains(name)) {
...
}
Since you don't seem to care about the order of the names, but only want to test if the collection contains a name or not, a HashSet is the best data structure: HashSet.contains() runs in constant time (O(1)), whereas List.contains(), for example, is O(n).
Read the collections tutorial.
You can loop through your array instead:
String name = kb.nextLine();
if(contains(name)) {
System.out.println("you are verified you may use the lift");
}
public boolean contains(String name) {
String [] names = {"barry", "matty", "olly","joey"};
for (int i = 0; i < names.length; i++) {
if(names[i].equals(name)) {
System.out.println("you are verified you may use the lift");
}
}
Or you can use List.contains(), in this case you have to add your names inside List instead of regular array.
For Example:
String[] names = {"barry", "matty", "olly", "joey"};
List<String> namesList= Arrays.asList(names);
if (namesList.contains(name)) {
System.out.println("you are verified you may use the lift");
}
Using ArrayList and List instead of Array of Strings:
List<String>names = new ArrayList<String>(names);
name = kb.nextLine();
if(names.indexOf(name)>-1)System.out.println("you are verified you may use the lift");
This because of the indexof in List returns -1 if not found or the index of the founded element, starting with 0.
I think that also
if(names.contains(name))System.out.println("you are verified you may use the lift");
works
Use a for loop
get input
for int i = 0, i < array size i++
if input.equals(array[i]) then do stuff
If you switch to an arraylist, you can do if(array.contains(input))