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
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 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);
I have a .txt file that looks like this:
Mathematics:MTH105
Science:SCI205
Computer Science:CPS301
...
And I have an assignment that requires that I read file and place each line into an array that should look like this:
subjectsArray[][] = {
{"Mathematics", "MTH105"},
{"Science", "SCI205"},
{"Computer Science", "CPS301"}
};
I am getting a compile error when I attempt to add the contents of the file to a 2-dimensional array:
private static String[][] getFileContents(File file) {
Scanner scanner = null;
ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>();
//Place the contents of the file in an array and return the array
try {
scanner = new Scanner(file);
int i = 0;
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineSplit = line.split(":");
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]>
}
i++;
}
return subjectsArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return null;
}
Error reads:
The type of the expression must be an array type but it resolved to ArrayList<String[][]>
I am new to multi-dimensional arrays and not sure what it is I'm doing wrong. Can someone tell me what I'm doing wrong?
Your first mistake is the selection of the type for the result: this type
ArrayList<String[][]>
represents a three-dimensional structure - a list of 2D arrays. What you need is a two-dimensional structure, e.g.
ArrayList<String[]>
So the first fix is this:
List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface
Once this is done, the rest of the code flows by itself: you do not need the inner for loop, it gets replaced by a single line:
subjectsArray.add(lineSplit);
The final fix is the return line: you need to convert the List<String[]> to String[][], which can be done by calling toArray(), like this:
return subjectsArray.toArray(new String[subjectsArray.size()][]);
I think you are trying to use an ArrayList method on a String. I am not sure that is possible. The simplest way to do what you need I think is:
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j]=lineSplit[j];
}
This is my code below, I get an java.lang.IndexOutOfBoundsException & I can't fix it? I am supposed to STOP the error from coming up because I have over 100 names in the file!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ArrayPractice1 {
public static void main(String[] args) throws FileNotFoundException
{
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 -1; i++){
System.out.println(names[i]);
}
}
}
youre not working with an ArrayList of Strings, you're working with a plain array of Strings.
seems like youre getting more than 100 items from scan.hasNext() and so you eventually try to access names[100] and get the exception you describe
instead, you could use this:
ArrayList<String> names = new ArrayList<String>();
and then
while (scan.hasNext()){
names.add(scan.nextLine());
}
and you wont have to worry about knowing the exact size beforehand
If the size of the input is not known at compile time, consider using an ArrayList instead of an array.
Just add the elements to the ArrayList using names.add(scan.nextLine()):
ArrayList<String> names = new ArrayList<String>();
while (scan.hasNext()) {
names.add(scan.nextLine())
}
You are giving 100 as the size of array.If your file have more than 100 lines, definitely it will throw exception
change the condition in your while loop to
while (scan.hasNext() && index < 100)
this will stop the read loop after you fill up the array
Why not making it independent from any upper limit? Use an ArrayList:
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
while (scan.hasNext()){
names.add(scan.nextLine());
}
for(String name : names){
System.out.println(name);
}