Read in lines of text file to separate arrays using indexOf - java

I want to separate the elements of a text file into different arrays based of whether or not the line contains a question mark. Here is as far as I got.
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
ArrayList<String> Questions = new ArrayList();
ArrayList<String> Other = new ArrayList();
while (fScan.hasNextLine())
{
if(fScan.nextLine.indexOf("?"))
{
Questions.add(fScan.nextLine());
}
Other.add(fScan.nextLine());
}

Quite a few issues there
nextLine() actually returns the next line and moves on the scanner, so you'll need to read once instead
indexOf returns an int, not a boolean, I'm guessing you're more use to C++? You can use any of the following instead:
indexOf("?") >=0
contains("?")
matches("\?") etc.
please follow the java ways and use camelCase for vars...
Code
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("foo.txt"));
List<String> questions = new ArrayList<String>();
List<String> other = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("?")) {
questions.add(line);
} else {
other.add(line);
}
}
System.out.println(questions);
System.out.println(other);
}
foo.txt
line without question mark
line with question mark?
another line

Related

How to populate array with text from a file using Scanner and then randomly select the text from the array?

I have a text file that contains a list of films:
Kangaroo Jack
Superman
Shawshank Redemption
Aladdin
What I want to do is pass all of these films into an array and then randomly select a film from the array. However it seems to always select 'Aladdin' and I am not sure what I am doing wrong? How can I randomly select films from the array?
public static void main(String[] args) throws FileNotFoundException {
String[] movieList = {};
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Reads the whole file
movieList = line.split("//s");
//splits the string by white space characters meaning we will get the full word(s) per line
}
boolean weArePlaying = true;
while (playing) {
char[] randomWordToGuess = movieList[random.nextInt(movieList.length)].toLowerCase().toCharArray();
int wordLength = randomWordToGuess.length;
char[] playerGuess = new char[wordLength];
boolean wordCompleted = false;
...
}
movieList = Line.Split("//")
This line is always overwriting movielist with the last line in the file: Alladin
Rather write it like the following:
ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList.add(line);
}
It's important to note that your original approach would have succeeded if all the movie names were on the same line and had no white spice in between their names like this:
KangarooJack Superman ShawshankRedemption Aladdin
loop also wouldn't have been necessary. So it could have been written like this:
String[] movieList = {};
String line = fileScanner.nextLine();
movieList = line.split("//s");
And if you want to get really wild...
String[] movieList = fileScanner.nextLine().split("//");
movieList = line.split("//s"); is only assigning the last movie to the array, so there is only ever one element in the array. Instead, you need to read each line and assign it to an entry in the array.
Maybe something more like...
String[] movieList = new String[4];
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int index = 0;
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList[index] = line;
index++;
}
This assumes that there are only 4 lines in the file, if there aren't then you will have IndexOutOfBoundsException.
You could guard against this in a number of ways. You could put the number of expected lines as the first line of the file and then create the array based on that or you could exit the while-loop when the array is full or you could use a ArrayList, which is a type of dynamic array

Why is this java nested while loop not working?

Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;
public class Warehouse {
static private String[] eachStockElem = new String[5];
static private String[] eachInputElem = new String[5];
public static void main(String[] args) throws Exception {
Scanner str = new Scanner(new File("a.txt"));
Scanner ip = new Scanner(new File("b.txt"));
PrintStream st_w = new PrintStream("a.txt");
PrintStream tx = new PrintStream("c.txt");
ArrayList<String[]> stockArrayList = new ArrayList<>();
ArrayList<String[]> inputArrayList = new ArrayList<>();
ArrayList<String[]> txArrayList = new ArrayList<>();
String eachTxElem[] = new String[6];
int tx_id=0;
int temp_quantity=0;
int count=0;
try {
while (ip.hasNextLine()) {
eachInputElem = ip.nextLine().split(",");
inputArrayList.add(eachInputElem);
while (str.hasNextLine()) { //this while not working!
eachStockElem = str.nextLine().split(",");
stockArrayList.add(eachStockElem);
count++;
//do comparing operation
break;
}
}
}
catch(NullPointerException e){
System.out.print("");
}
System.out.println(count);
str.close();
ip.close();
tx.close();
}
}
By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:
The name of the file to use as the destination of this print stream.
If the file exists, then it will be truncated to zero size; otherwise,
a new file will be created. The output will be written to the file and
is buffered.
The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.
At this line,
PrintStream st_w = new PrintStream("a.txt");
the program is writing the output in the same input file. Change the name of this output file and execute your test case.

Sentinel value at the end of a file?

I read in the contents of my File likewise:
List<String> list = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(file));
while( scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
At the EOF I want to send the String "###" to act as a Sentinel Value to know that its the end. However, I do not have "###" in the File that is being read into. Any suggestions on how I might approach this?
List<String> list = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(file));
while( scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
list.add("###");
Just add the line list.add("###"); after your while loop.
You'll know you've read the entire file in by then, so just add the constant string. You may want to consider separating out the string for readability with something like:
public static final String SENTINEL = "###";

Trouble reading file, program looks good not understanding why its outputting null

Hey guys I'm trying to read in a file which I have done many times before, but It keeps outputting "null" for however many lines of code exist in the .
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
String[] item = new String[25];
Scanner fileInput;
File inFile = new File("dictionary.txt");
try {
fileInput = new Scanner(inFile);
int newItem = 0;
while (fileInput.hasNext())
{
item[newItem++] = fileInput.nextLine();
System.out.println(item[newItem]);
}
}
catch(FileNotFoundException e){System.out.println(e); }
txt file. please help.
You increment newItem and then you print item[newItem]. It always return null because you have not written anything yet in item for the new index.
Try:
while (fileInput.hasNext()) {
item[newItem] = fileInput.nextLine();
System.out.println(item[newItem]);
newItem++;
}
It's because of newItem++, which returns the value and then increments it.
So, you start by setting item[x] = ...; - but then print out item[x+1];

file input from the user

I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.

Categories

Resources