Using Scanner to read file - java

I am using Scanner to read the text file which contains *, spaces and alphabets. Two or more spaces can occur one after the other. Eg:
**** AAAAA* * ****
******* AAAAAA*** *
I have written the following code:
lineTokenizer = new Scanner(s.nextLine());
int i=0;
if (lineTokenizer.hasNext()) {
//lineTokenizer.useDelimiter("\\s");
System.out.println(lineTokenizer.next());
//maze[0][i]=lineTokenizer.next();
i++;
}
The lineTokenizer doesn't read beyond the * from the input file not are the characters getting stored in the maze array. Can you tell me where I'm going wrong? Thanks!

You could also use FileInputStreams to read the file with a BufferedReader.
I personnally use the Scanner only for console input.

I think you should be using loops instead of just if.
Try changing the 3rd line to:
while (lineTokenizer.hasNext())

Since you are using an if condition, the pointer is not moving ahead. You should use a loop to continuously read data from scanner. Hope that helps.

I guess the code is changed many times while you tried different stuff.
I don't know how you handle the initialization of maze but to avoid any ArrayIndexOutOfBounds I would use a List in a List instead.
I made some guesses about what you wanted and propose this:
List<List<String>> maze = new ArrayList<>();
Scanner s = new Scanner("**** AAAAA* * ****\n ******* AAAAAA*** *");
while (s.hasNextLine()) {
List<String> line = new ArrayList<>();
Scanner lineTokenizer = new Scanner(s.nextLine());
lineTokenizer.useDelimiter("\\s+");
while (lineTokenizer.hasNext()) {
String data = lineTokenizer.next();
System.out.println(data);
line.add(data);
}
lineTokenizer.close();
maze.add(line);
}
s.close();
I did not fully understand your goals. Does this do about what you want?
The code above will give you the following list: [[****, AAAAA*, *, ****], [*******, AAAAAA***, *]]

Related

Why am I getting an InputMismatchException with?

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:
Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2
When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an int).
public void fileScanner(File toScan) throws FileNotFoundException {
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",");
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.
You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",|\\r\\n");
while (sc.hasNext()) {
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
}
OUTPUT:-
Abbotsford
2310
2
Adams
1967
1
Algoma
3167
2
The delimiter you're using is comma(,)
The system looks for the next comma, which comes only after Adams. So the input for the system looks like 2 Adams which is obviously not an Int , rather a String and hence the inputMisMatch.
If you make your data something like below, your code would work great.
Abbotsford,2310,2,
Adams,1967,1,
Algoma,3167,2,
Also I see there's no loop to read all the data. Your code will read just the first line.

Decision making and loop

I am brand new to Java (2 weeks), basically I am trying to do a Triangle problem. I need to input a text file that looks like this:
2 2 2
3 3 2
3 x 4
I can make it read the file and display it correctly, however I need it to display "Equilateral" " Isosceles" "Scalene" or not a triangle because... I cannot figure out how to get my outputs based on the input from the text file. Here is what I have so far.
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Which is basically nothing. I know I need 3 arrays. Can someone jumpstart me in the right direction?
Thanks
You need to set sc.nextLine() to a variable to use instead of printing it out as an output immediately. If the sets of three numbers come in a single line, you may want to utilize the split() method, which is pretty easy to use when you understand arrays.
To get you started:
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
String firstLine = sc.nextLine();
String[] sides = firstLine.split(" ");// Get the numbers in between the spaces
// use the individual side lengths for the first triangle as you need
// Next iteration works through the next triangle.
}
You're headed in the right direction. I suggest checking out the following methods:
String.split() docs here
Integer.parseInt() docs here
Those, combined with a little bit of your own logic, should be enough to get you across the finish line.

java- use scanner to read in and process one piece of information at a time

I am trying to use scanner to read in several lines of input at a time. I reckon that there is something wrong with either the way I use the loop, or the way I read in information. Nothing was stored in the output array. I commented my question in the code. Can someone please help? Thank you!
Scanner c = new Scanner (System.in);
while (c.hasNextLine()){
ArrayList <Integer> record= new ArrayList <Integer> (); // next time the while loop runs, I expect the list record to be initialized again
String numbers = c.nextLine();
int n = Integer.parseInt(numbers);
for (int i=0; i<n; i++){
String info = c.nextLine();//then read the following n lines use for loop
int length = info.length(); //get the length of each line
record.add(length);
}
putRecordinArray(record);//some other function to process each record(a block of several lines processed each time by the while loop)
}
//here I tried to print out the array A generated by other function, but nothing was stored.
}
Your Arraylist name is records but you are calling it with record which is records without the 's'. You have to add the 's'.
example of one of your calling statements.
record.add(length);
change to:
records.add(length);
also:
putRecordinArray(record);
change to:
putRecordinArray(records);
Hope this helps.

Java - Reading in value from text

OK so I have read plenty of examples on here dealing with reading in lines from a text file and splitting them up but im not quite sure I understand how to do it in my situation. I have a file that is basically separated into three columns as follows:
START 5000
FIND A
PLUS B
SAVE C
STOP
A, INT 69
B, INT -420
C, CRAZY 008484342
What I am trying to do is read in this .txt file containing the above information. I figured reading in the file line by line would be best, then splitting it into the correct columns. The problem that I am having is the fact that the 1st column is not always here. It is an optional one. If they were all filled in, im almost positive I could just use use something like
String[] array1 = myLine.split(",");
Another idea I had was to split the line based on ,'s then split the line again based on " " but im not exactly sure how to do this. Maybe somthing like
String[] array1 = myLine.split(",");
String[] array2 = array1[1].split(" ");
Also, is there any way to just read in the file and store each row into like (String, String String) then just check for ints vs strings? Maybe in a try catch? or like:
Scanner input = new Scanner(File);
while(input.hasNext()){
String str = input.next();
try{
b = Integer.parseInt(str);
}
I am not sure if this is as hard as a task as im making it but maybe so... Any help with this topic would be appreciated.
After looking over some more code, I have the following to start:
public static void main(String[] args) {
String file ="TEST.txt";
try{
FileReader input = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(input);
String line;
while ((line = bufferReader.readLine()) != null) {
// Is this where I would attempt to split the lines?
System.out.println(line);
}
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
So with this, I am successfully reading in the file and displaying the information back to the output console. Now for separating the lines... Ill be posting my work as I go, any help and or suggestions would be appreciated! Also thank you to those who have already commented with helping to split the stings, ill be attempting this now!
You can combine both expressions and only checked the array's length. e.g.:
String[] array = line.trim().split("[, ]+");
switch(array.length) {
case 2:
// do something
break;
case 3:
// do something
break;
default:
// something wrong
break;
}
The trim() in the line is for avoid empty string in the first element array.
Use split(" +") which will split on any numbers of spaces. This works because split handles regex. If you want to split on any type of whitespace you can also use split("\\s+). After you get the array check if it has 2 or 3 elements and handle it accordingly.
Well ... I don't have the time yet for a long answer. But I'd recommend you to read a little bit about regular expressions (RegEx) and how it is used in java ... I am sure this will help you with this problem and a huge amount of future problems like this ...
Try this: http://www.vogella.com/articles/JavaRegularExpressions/article.html ... of this http://docs.oracle.com/javase/tutorial/essential/regex/ ... if the first one does not help ;)

Word Count from a file

I'm at the start of writing my program (this is for a class) and I'm running into trouble to just write it down. Here's a list of goals I am hoping to meet.
It is a method given a .txt file (using java.io.File)
It needs to read the file and split the words, duplicates are allowed. (I plan to use String.split and util.regex.Pattern to work out whitespace and punctuation)
I'm aiming to put the words in a 1D array and then just find the length of the array.
The problem I'm running into is parsing the txt file. I was told in class that Scanner can, but I'm not finding it while R(ing)TFM. I guess I'm asking for some directions in the API that helps me understand how to read a file with Scanner. Once I can get it to put each word in the array I should be in the clear.
EDIT: I figured out what I needed to do thanks to everyone's help and input. My final snippet ends up looking like this, should anyone in the future come across this question.
Scanner in = new Scanner(file).useDelimiter(" ");
ArrayList<String> prepwords=new ArrayList<String>();
while(in.hasNext())
prepwords.add(in.next());
return prepwords; //returns an ArrayList without spaces but still has punctuation
I had to throw IOExceptions since java hates not being sure a file exists, so if you run into "FileNotFoundException", you need to import and throw IOException. At the very least this worked for me. Thank you everyone for your input!
BufferedReader input = new BufferedReader(new FileReader(filename));
input.readLine();
This is what I use to read from files. Note that you have to handle the IOException
Here is a link to the JSE 6.0 Scanner API
Here is the info you need to complete your project:
1. Use the Scanner(File) constructor.
2. Use a loop that is, essentially this:
a. Scanner blam = new Scanner(theInputFile);
b. Map<String, Integer> wordMap = new HashMap<String, Integer>();
c. Set<String> wordSet = new HashSet<String>();
d. while (blam.hasNextLine)
e. String nextLine = blam.nextLine();
f. Split nextLine into words (head about the read String.split() method).
g. If you need a count of words: for each word on the line, check if the word is in the map, if it is, increment the count. If not, add it to the map. This uses the wordMap (you dont need wordSet for this solution).
h. If you just need to track the words, add each word on the line to the set. This uses the wordSet (you dont need wordMap for this solution).
3. that is all.
If you dont need either the map or the set, then use a List<String> and either an ArrayList or a LinkedList. If you dont need random access to the words, LinkedList is the way to go.
Something simple:
//variables you need
File file = new File("someTextFile.txt");//put your file here
Scanner scanFile = new Scanner(new FileReader(file));//create scanner
ArrayList<String> words = new ArrayList<String>();//just a place to put the words
String theWord;//temporary variable for words
//loop through file
//this looks at the .txt file for every word (moreover, looks for white spaces)
while (scanFile.hasNext())//check if there is another word
{
theWord = scanFile.next();//get next word
words.add(theWord);//add word to list
//if you dont want to add the word to the list
//you can easily do your split logic here
}
//print the list of words
System.out.println("Total amount of words is: " + words.size);
for(int i = 0; i<words.size(); i++)
{
System.out.println("Word at " + i + ": " + words.get(i));
}
Source:
http://www.dreamincode.net/forums/topic/229265-reading-in-words-from-text-file-using-scanner/

Categories