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);
Related
I have the following code:
package sportsCardsTracker;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.stream.Collectors;
public class Test_Mark6 {
public static ArrayList<String> listingNameList;
public static ArrayList<String> finalNamesList;
public static void main(String[] args) throws IOException, ParseException {
listingNameList = new ArrayList();
listingNameList.add("LeBron James 2017-18 Hoops Card");
listingNameList.add("Stephen Curry Auto Patch, HOT INVESTMENTS!");
listingNameList.add("Michael Jordan 1998 Jersey Worn Card");
ArrayList<String> playersNamesList = new ArrayList();
playersNamesList.add("LeBron James");
playersNamesList.add("Stephen Curry");
playersNamesList.add("Michael Jordan");
finalNamesList = new ArrayList();
String directory = System.getProperty("user.dir");
File file = new File(directory + "/src/sportsCardsTracker/CardPrices.csv");
FileWriter fw = new FileWriter(file, false); //true to not over ride
for (int i = 0; i < listingNameList.size(); i++) {
for (String listingNames : listingNameList) {
List<String> result = NBARostersScraper_Mark3.getNBARoster().stream().map(String::toLowerCase).collect(Collectors.toList());
boolean valueContained = result.stream().anyMatch(s -> listingNames.toLowerCase().matches(".*" + s + ".*"));
if(valueContained == true) {
finalNamesList.add(//The players' name);
}
}
fw.write(String.format("%s, %s\n", finalNamesList.get(i)));
}
}
}
Basically, in the listingsNameList, I have the listing's names and in the playersNamesList, I have all the players' names. What I would like is that, if the code matches the names between the two arrayList and find a player's name, it should returns the players' only.
For example, instead of "LeBron James 2017-18 Hoops Card" it should return "Lebron James" only. If it does not find anything, then just return the listing's name. So far, I have created a new ArrayList namely finalNamesList, my idea would be using an if statement (if match found then add players' name to finalNamesList, if not add the listing' name to finalNamesList). However the code above is not working and it is just adding all of the names in the listingNameList to the finalNamesList. I suspect that the way I grab the index is wrong - but I don't know how to fix it.
The method you are using to match a pattern that seems wrong. Instead of "match()" you can use string contains method as below.
List<String> temp = new ArrayList<>();
for (String listingNames : listingNameList) {
temp = playersNamesList.parallelStream().filter(s -> listingNames.toLowerCase().contains(s.toLowerCase())).map(s -> s).collect(Collectors.toList());
if(temp.size() > 0){
System.out.println(temp.get(0));
//fw.write(String.format("%s, %s\n", temp.get(0));
}
}
One more thing, You don't need to use 2 for loop here, with one loop you can achieve your output.
Though You can still optimize this code, I have taken the temp list above that you can avoid.
The code:
public static void main(String[] args) throws Exception{
Scanner scn = new Scanner(new File ("kektura.csv"));
int kezd = 0;
List <String> indul = new ArrayList<>();
List <String> veg = new ArrayList<>();
List <Double> hossz = new ArrayList<>();
List <Integer> emel = new ArrayList<>();
List <Integer> lejt = new ArrayList<>();
List <Boolean> pecset = new ArrayList<>();
kezd=scn.nextInt();
scn.nextLine();
while(scn.hasNextLine())
{
scn.useDelimiter(";");
indul.add(scn.next());
veg.add(scn.next());
hossz.add(scn.nextDouble());
emel.add(scn.nextInt());
lejt.add(scn.nextInt());
if(scn.next()=="n")
{
pecset.add(Boolean.TRUE);
}
else
{
pecset.add(Boolean.FALSE);
}
scn.nextLine();
}
for(Object x : pecset)
{
System.out.println(x);
}
scn.close();
}
And the file (It's a csv file, it has more lines, but they are the same pattern):
192
Sumeg, vasutallomas;Sumeg, buszpalyaudvar;1,208;16;6;n
Sumeg, buszpalyaudvar;Mogyorosi-domb, geologiai bemutatohely;1,512;24;8;n
Mogyorosi-domb, geologiai bemutatohely;Sumegi bazaltbanya vasutallomas;1,576;13;43;n
Sumegi bazaltbanya vasutallomas;Sarvaly erdeszhaz, pecsetelohely;2,101;69;18;i
I have a problem with reading this.
Read the first line, it's okay.
But the second line isn't good, because (i think) the delimeter reads until the ( ; ) character, but in the end of the line, there's not a ( ; ) .
The last line of the while, I wrote scn.nextLine to read the \n character, but it doesn't work.
I know thats a possible way, to read the line, and split it, but it's a school project, and the teacher told us to find out another solution.
Is there a way, to solve this?
As your teacher wants you to find another solution, I propose to use a BufferedReader to read the file in single lines. For each line you can then use String#split() and finally convert the respective parts to the required type (Integer#parseInt() etc).
However, as this is stated as a homework question, I will not provide a full example.
I'm writing the code of my first Java game right now and I have a problem with ArrayList. I have one, with elements like nicknames and scores, to be specific I create it from the text file(code below):
static ArrayList<String> results = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(ranking));
String line = br.readLine();
results.add(line);
while(line != null) {
line = br.readLine();
results.add(line);
}
br.close();
So the file looks like this:
nick1
score1
nick2
score2
...
I would like to make a ranking with top 10 best results, my idea is to make the class with the fields nick and score and somehow assign that fields to appriopriate ones from the ArrayList. Maybe I can do this like this:(?)
for(int i = 0;i<results.size();i=i+2){
nick = results.get(i);
}
for(int i = 1;i<results.size();i=i+2){
score = results.get(i);
}
Then I would create a new ArrayList, which would be in the type of that new class. But my problem is that I don't exactly know how I can connect values from 'old' ArrayList with the paramaters of future type of new ArrayList. The new one should be like:
static ArrayList<Ranking> resultsAfterModification = new ArrayList<Ranking>();
Ranking rank = new Ranking(nick, score);
Then I can easily compare players' scores and make a solid ranking.
You can create a class Player that contains the name and score of each player. The Player class should implement the Comparable interface which is Java's way of figuring out the logical order of elements in a collection:
public class Player implements Comparable<Player>
{
private String _name;
private double _score;
public Player(String name, double score)
{
this._name = name;
this._score = score;
}
public String getName()
{
return this._name;
}
public double getScore()
{
return this._score;
}
// Since you probably want to sort the players in
// descending order, I'm comparing otherScore to this._score.
#Override
public int compareTo(Player otherScore)
{
return Double.compare(otherScore._score, this._score);
}
#Override
public String toString()
{
return "Name: " + this._name + ", Score: " + Double.toString(this._score);
}
}
Once you've created the Player class, you can read both name and score in one go and use the Collections utility class to sort the Player list. Last but not least, you could grab the top ten by using the subList method: (this assumes that the file will have a score for each name and the file will be in the format you specified above)
public static void main(String[] args)
{
List<Player> results = new ArrayList<Player>();
BufferedReader br;
try
{
br = new BufferedReader(new FileReader("myFile.txt"));
String line = br.readLine();
while(line != null)
{
String name = line;
double score = Double.parseDouble(br.readLine());
results.add(new Player(name, score));
line = br.readLine();
}
br.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// Sort using the java.util.Collections utility class
// Sorting will modify your original list so make a copy
// if you need to keep it as is.
Collections.sort(results);
// Top 10
List<Player> top10 = results.subList(0, 10);
}
1) You should program by Interface (List instead of ArrayList in declared type) here because you don't use methods specific to ArrayList.
List<Ranking> resultsAfterModification = new ArrayList<Ranking>();
2)
Then I would create a new ArrayList, which would be in the type of
that new class. But my problem is that I don't exactly know how I can
connect values from 'old' ArrayList with the paramaters of future type
of new ArrayList.
To do it, you don't need many changes.
Your idea a is little too complex because finally you perform two mappings : one where you store from read line to List of String and another one where you store from List of String to List of Ranking .
You can direct map read line to List of Ranking.
List<Ranking> rankings = new ArrayList<Ranking>();
BufferedReader br = new BufferedReader(new FileReader(ranking));
String nick = null;
while ( (nick = br.readLine()) != null){
String score = br.readLine();
rankings.add(new Ranking(nick, score));
}
You can save array in file :
1 use, FileInputStram and FileOuputStream to write and read array object to file.
2 use Gson library to save and load array as json
3 write as normal textfile like below:
Player 1
Score 1
Player 2
Score 2
....
ArrayList<Player> list=new ArrayList();
Scanner sc=new Scanner(new File("filepath.txt"));
While(sc.hasNextLine()){
Player p=new Player();
p.name=sc.nextLine();
If(sc.hasNextFloat()){
p.score=sc.nextFloat();
list.add(p);
}
}
Arrays.sort(list,...);
And can sort array by Arrays.sort()
So your Ranking class might look like
public class Ranking {
public String nick;
public int score;
}
I think the nick and score are two ArrayList containing nicks and scores respectively.
So to create a common ArrayList, if the sizes of nick and score are the same, you might do something like this.
static ArrayList<Ranking> resultsAfterModification = new ArrayList<Ranking>();
for(int i = 0; i < nick.size(); i++) {
Ranking rank = new Ranking(nick.get(i), score.get(i));
resultsAfterModification.add(rank);
}
Now you need to write your own comparator to sort the values inside resultsAfterModification
Collections.sort(resultsAfterModification, new Comparator<Ranking>() {
#Override
public int compare(Ranking r1, Ranking r2) {
if (r1.score > r2.score)
return 1;
if (r1.score < r2.score)
return -1;
return 0;
}
});
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 );
I am unsure on how to give the user an option to add / delete a name from the existing text file. The current code works fine and reads in names from the text file. Could someone give me a hand on this?
import java.io.File;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
String[] names = new String[100];
Scanner scan = new Scanner(new File("names.txt"));
int index = 0;
while (scan.hasNext()){
names[index]=(scan.nextLine());
index++;
}
for(int i = 0; i < index; i++){
System.out.println(names[i]);
}
scan.close();
}
}
It is possible, almost everything is, but you'll find it very difficult to do using arrays.
I would instead use an ArrayList which is similar, but much, much better than just regular ol' arrays.
A String ArrayList is defined like so:
ArrayList<String> names = new ArrayList<String>();
You can add using the add function of the ArrayList:
while (scan.hasNext())
names.add(scan.nextLine());
Then, to remove a name from the text file, just remove it from the names ArrayList using the remove function, and write the modified ArrayList to the file:
names.remove("Some Name Here");
PrintWriter writer = new PrintWriter("names.txt", "UTF-8");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
Likewise, to add a new name to the file, just add the new name to the ArrayList before you write it to the file, using the add function