Splitting a line from a textfile into two separate Arrays - java

I must apologize in advance if this question has been answered, I have not been able to find an answer to this problem on the forum thus far.
I am working on a Project Euler Problem, Problem 54 to be exact, and I am required to read in 1000 lines of data, each line contains two randomly generated Poker hands, the first half of the line being Player 1's hand, the second being Player 2's.
Below is an example of the layout of the document:
8CTSKC9H4S 7D2S5D3SAC
5CAD5DAC9C 7C5H8DTDKS
3H7H6SKCJS QHTDJC2D8S
TH8H5CQSTC 9H4DJCKSJS
What I have done thus far is manually make two documents copying the second "Hand" from each line and adding that to the new document. However I did that twice and came up with two different results, so I think I am making an error somewhere with all the copying.
Below is an example of the the above function I used:
ArrayList<String> player1 = new ArrayList<String>();
ArrayList<String> player2 = new ArrayList<String>();
String file1 = "FilePath1";
String file2 = "FilePath2";
Scanner input1 = new Scanner(new File(file1));
while(input1.hasNext()) {
player1.add(input1.nextLine());
}
Scanner input2 = new Scanner(new File(file2));
while(input2.hasNext()) {
player2.add(input2.nextLine());
}
input1.close();
input2.close();
What I would like to know is how could I read only the first hand into an ArrayList, and then only the second hand into another one. Without having to create two separate documents and risk compromising the data. I am not sure how I would be able to use the Split function here if that is the way to go. I am fairly new to programming, I am trying to teach myself, so I apologize if this is a overly simple problem.
Thank you very much in advance

You can split on space (all whitespace)
For example:
String currLine = input1.nextLine();
//This only needed if you are not sure if the input will have leading/trailing space
currLine = currLine.trim();
String[] split = currLine.split("\\s+");
//Ensuring the line read was properly split
if(split.length == 2) {
//split[0] will have the first hand
player1.add(split[0]);
//split[1] will have the second hand
player2.add(split[1]);
}

Related

In Java, how do I read both Strings and Doubles from the same txt file? [duplicate]

I am creating a simple program to data read from a text file. The file stores information about a person, with the name, age and a number on each line:
Eg: File format per line
Francis Bacon 50 2
I can read in a file no problem if it is just text, but I am confused on how to differentiate between text and numbers. Here is a look at my code:
import java.io.*;
public class Test{
private People people[] = new People[5];
public Test(){
BufferedReader input;
input = new BufferedReader(new FileReader("People.txt"));// file to be readfrom
String fileLine;
int i = 0;
while (test != null){
fileLine = input.readLine();
// Confused as to how to parse this line into seperate parts and store in object:
// eg:
people[i].addName(fileLine - part 1);
people[i].addBookNo(fileLine - part 2);
people[i].addRating(fileLine - part 3)
i++
}
}
}
I strongly suggest you use the Scanner class instead. That class provides you with methods such as nextInt and so on.
You could use it to read from the file directly like this:
Scanner s = new Scanner(new File("People.txt"));
while (s.hasNext()) {
people[i].addName(s.next());
people[i].addBookNo(s.nextInt());
people[i].addRating(s.nextInt());
}
(Just realized that you may have spaces in the name. That complicates things slightly, but I would still consider using a scanner.)
An alternative solution would be to use a regular expression and groups to parse the parts. Something like this should do:
(.*?)\s+(\d+)\s+(\d+)
The following regex works on these 3 cases, breaking them into 3 matched groups.
Regex
(.*)\s+(\d+)\s+(\d+)
Cases
Francis Bacon 50 2
Jill St. John 20 20
St. Francis Xavier III 3 3
If you want to do in this way, you can try doing like this :
Fixing the way data will be present in the file, say
firstName.lastName.age.number;
Then you can write code to read data upto . and store it in a variable (you will be knowing what it is meant for) and after ";" there will be second entry.

Reading from two textfiles: one array to keep, one array to omit from textfile

This is the problem:
I'm given a text with certain words and characters that I am to omit. I am to create a method that will return an array of words with two file arguments like this:
public Word[] keyWordsList(File inputFile1, File inputFile2)
inputFile2 contains a bunch of words and punctuations that I am to ignore from what is contained in inputFile1.
inputFile2 contains the following:
of the a in on , . ?
inputFile1 contains a whole paragraph of text, and I am to push each of those words into the Word[].
I just need help in understanding how I can accurately place all the words and omit the ones from inputFile2 because inputFile2 contains both string and character primitive types.
This is my code to solve this issue (which has been fairly successful) but I just don't know how to handle the exception where the punctuation is right after the word.
Scanner ignore = new Scanner(inputFile2);
Scanner important = new Scanner(inputFile1);
ArrayList<String> ignoreArray = new ArrayList<>();
while (ignore.hasNext()) {
String ignoreWord = ignore.next();
ignoreArray.add(ignoreWord);
}
ArrayList<String> importantWords = new ArrayList<>();
while (important.hasNext()) {
String word = important.next();
if (ignoreArray.contains(word))
continue;
else
importantWords.add(word);
}
I'm getting results like this:
[This, is, input, file, to, create, key, words, list., If, we, ever, want, to, know, how, background, job, works,, fastest, way, to, find, k, smallest, elements, an, array,,] etc.etc.
From this:
This is the input file to create key words list.
If we ever want to know how background job works, fastest way to find k smallest elements in an array,
I would appreciate any help. Thank you!

convert String to arraylist of integers using wrapper class

Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.

How do I check see a newline character with my scanner if I'm using a delimiter?

I'm trying to make an undirected graph with some of the nodes (not all, unlike my example) being connected to one another. So my input format will look like
3
1:2,3
2:1,3
3:1,2
Meaning there's three nodes in all, and 1 is connected to 2 and 3, 2 is connected to 1 and 3 and so on.
However, I cannot understand how to take the input in a meaningful way. Here's what I've got so far.
public Graph createGraph() {
Scanner scan = new Scanner(System.in).useDelimiter("[:|,|\\n]");
int graphSize = scan.nextInt();
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
while (!scan.hasNext("\\n")) {
System.out.println("Scanned: " + scan.nextInt());
}
}
return new Graph(graphSize);
}
Can my
while (!scan.hasNext("\\n"))
see the newline character when I'm using a delimiter on it?
In my opinion, you shouldn't be using those delimiters if they are meaningful tokens. In the second line for example, the first integer doesn't have the same meaning as the others, so the : is meaningful and should be scanned, even if only to be discarded later. , however doesn't change the meaning of the tokens that are separated by it, so it's safe to use as a delimiter : you can grab integers as long as they are delimited by ,, they still have the same meaning.
So in conclusion, I would use , as a delimiter and check manually for \nand : so I can adapt my code behaviour when I encounter them.
yup, scanner can definitely detect new line. infact you dont even have to explicitly specify it. just use
scan.hasNextLine()
which essentially keeps going as long as there are lines in your input
Edit
Why dont you read everything first and then use your for loop?
Alright I figured it out. It's not the prettiest code I've ever written, but it gets the job done.
public Graph createGraph() {
Scanner scan = new Scanner(System.in);
number = scan.nextLine();
graphSize = Integer.valueOf(number);
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
number = scan.nextLine();
Scanner reader = new Scanner(number).useDelimiter(",|:");
while (reader.hasNextByte()) {
System.out.println("Scanned: " + reader.nextInt());
}
}
return new Graph(graphSize);
}

using split to get rid of regexp from an Arraylist

I am trying to create a spell checker, but before I can do so I must read in two separate files. The first (the dictionary), I did file. The second is a novel for which I must spell check. Problem is, I need to remove all special characters that are not letters (regexp?) from the novel. I am trying to use the string.split, but am having no luck. I am testing this one a small section of the novel, test2.
This is the section of code I have...
public static void readFileBook() {
File f = new File("test2.txt");
ArrayList<String> list2 = new ArrayList<String>();
try {
Scanner input = new Scanner(f);
int i = 0;
while (input.hasNext()) {
String oliver = input.next();
list2.add(oliver);
String[] oliverArray = oliver.split("[.#]");
System.out.println(list2.get(i));
i++;
}
} catch (IOException e) { //opening failed
e.printStackTrace();
}
}`enter code here`
I started small with the '.' and '#' symbols. The System.out is just to check if things are working (they aren't), but output still has symbols.
I know there is probably a more elegant way of doing this, but the instructor a specific thing in find.
Any help would be appreciated.
so in you code
String oliver = input.next();
list2.add(oliver);
String[] oliverArray = oliver.split("[.#]");
System.out.println(list2.get(i));
you are (line by line)
reading input into String oliver
adding oliver to a list
splitting oliver into oliverArray which never gets used
printing the string in the list at position i
How would you know if this is working or not?

Categories

Resources