Counting the number of items in a file using java - java

I have a text file:
2|BATH BENCH|19.00
20|ORANGE BELL|1.42
04|BOILER ONION|1.78
I need to get the number of items which is 3 here using JAVA. This is my code:
int Flag=0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
Flag=Flag+1;
}
It is going in an infinite loop.
Can someone please help? Thank you.

You must get the next line to avoid an endless loop.
int Flag = 0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
sc.nextLine();
Flag++;
}

while (sc.hasNextLine()) {
Flag=Flag+1;
String line = sc.nextLine(); //Do whatever with line
}

In the code you have written
int Flag=0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) { // this line is just checking whether there is next line or not.
Flag=Flag+1;
}
When you write while (sc.hasNextLine()){} it check whether there is nextLine or not.
eg line 1 : abcdefg
line 2: hijklmnop
here your code will just be on line 1 and keep telling you that yes there is a nextLine.
Whereas when you write
while(sc.hasNextLine()){
sc.nextLine();
Flag++;
}
Scanner will read the line 1 and then because of sc.nextLine() it will go to line 2 and then when sc.hasNextLine() is checked it gives false.

Related

Java Scanner does not ignore new lines (\n)

I know that by default, the Scanner skips over whitespaces and newlines.
There is something wrong with my code because my Scanner does not ignore "\n".
For example: the input is "this is\na test." and the desired output should be ""this is a test."
this is what I did so far:
Scanner scan = new Scanner(System.in);
String token = scan.nextLine();
String[] output = token.split("\\s+");
for (int i = 0; i < output.length; i++) {
if (hashmap.containsKey(output[i])) {
output[i] = hashmap.get(output[i]);
}
System.out.print(output[i]);
if (i != output.length - 1) {
System.out.print(" ");
}
nextLine() ignores the specified delimiter (as optionally set by useDelimiter()), and reads to the end of the current line.
Since input is two lines:
this is
a test.
only the first line (this is) is returned.
You then split that on whitespace, so output will contain [this, is].
Since you never use the scanner again, the second line (a test.) will never be read.
In essence, your title is right on point: Java Scanner does not ignore new lines (\n)
It specifically processed the newline when you called nextLine().
You don't have to use a Scanner to do this
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String result = in.lines().collect(Collectors.joining(" "));
Or if you really want to use a Scanner this should also work
Scanner scanner = new Scanner(System.in);
Spliterator<String> si = Spliterators.spliteratorUnknownSize(scanner, Spliterator.ORDERED);
String result = StreamSupport.stream(si, false).collect(Collectors.joining(" "));

Java - Reading first word of text file

I am having trouble reading the first word of a text file. If the first word equals 'Circle' I want to create a new Circle object in my array.
FileInputStream fileIn = new FileInputStream("shapeFile.txt");
Scanner scan = new Scanner(fileIn);
while(scan.hasNextLine()) {
String shape = scan.next();
if(shape.equals("Circle")) {
myShapes.addShape(new Circle(scan.nextInt(), scan.nextInt(), scan.nextInt(), Color.RED));
}
}
I am getting the following error for the above code, pointing to the line String shape = scan.next();
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at shapes.ShapeManagement.main(ShapeManagement.java:151)
Java Result: 1
If anyone could help me resolve this I would be most grateful.
The reason your likely getting this exception is because scan.hasNextLine() can return true even if there are no tokens on that line. If you call scan.next() when there are no tokens after the marker, you will get the java.util.NoSuchElementException you are seeing.
So, swap out scan.hasNextLine() for scan.hasNext().
Alternatively you could swap out scan.next() for scan.nextLine() and then check whether the first word in that line was the one you are looking for. This could potentially be faster for files with large numbers of lines.
I hope this helps.
Link to the Scanner API for reference.
You may want to modify the code as follows:
FileInputStream fileIn = new FileInputStream("shapeFile.txt");
Scanner scan = new Scanner(fileIn);
int[] var1 = new int[3];
while(scan.hasNext()) {
String shape = scan.next();
if(shape.equals("Circle")) {
for(int i = 0; i < 3;i++) {
if(scan.hasNextInt()) {
var1[i] = scan.nextInt();
} else {
break;
}
}
myShapes.addShape(new Circle(var1[0], var1[1], var1[2], Color.RED));
}
}

Printing out the number of lines a file contains

At the moment my code does nothing when i input a valid .txt file. I would like to print the number of lines the file contains. Could anyone tell me why nothing is currently happening?
public class Task3
{
public static void main(String[] args) throws FileNotFoundException
{
// instance variables
int characterCount = 0;
int wordCount = 0;
int lineCount = 0;
// create a Scanner object to read in file name from console input
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name: ");
String filename = in.next();
File inputFile = new File(filename);
// create a Scanner object to read the actual text file
Scanner inFile = new Scanner(inputFile);
int lines = 0;
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
System.out.println(lines);
You're not reading lines from the file, you're reading them from standard input.
In this loop:
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
You are using the Scanner for System.in, not the scanner you created for the file. So the call to nextLine will wait for your input instead of going to the next line in the file. That's why it seems that nothing is happening.
Replace in.nextLine with inFile.nextLine and it will work.
Change:
in.nextLine();
To:
inFile.nextLine();
Add a System.out.println(inputFile.exists()) to see that you are not creating a new file.

How to determine the end of a line with a Scanner?

I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.
Here is the relevant part of my code, let me know if I left anything out :
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
String tempString = sc.next();
if (colorMap.containsKey(tempString) == true)
{
String word = tempString;
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(tempString + " ");
}
}
//closes the files
reader.close();
fWrite.close();
sc.close();
I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.
If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.
Lines are usually delimitted by \n or \r so if you need to check for it you can try doing it that way, though I'm not sure why you'd want to since you are already using nextLine() to read a whole line.
There is Scanner.hasNextLine() if you are worried about hasNext() not working for your specific case (not sure why it wouldn't though).
you can use the method hasNextLine to iterate the file line by line instead of word by word, then split the line by whitespaces and make your operations on the word
here is the same code using hasNextLine and split
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//get the line separator for the current platform
String newLine = System.getProperty("line.separator");
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNextLine())
{
// split the line by whitespaces [ \t\n\x0B\f\r]
String[] words = sc.nextLine().split("\\s");
for(String word : words)
{
if (colorMap.containsKey(word))
{
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(word + " ");
}
}
fWrite.write(newLine);
}
//closes the files
reader.close();
fWrite.close();
sc.close();
Wow I've been using java for 10 years and have never heard of scanner!
It appears to use white space delimiters by default so you can't tell when an end of line occurs.
Looks like you can change the delimiters of the scanner - see the example at Scanner Class:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Java parsing text file and preserving line breaks?

I have been researching how to do this and becoming a bit confused, I have tried so far with Scanner but that does not seem to preserve line breaks and I can't figure out how to make it determine if a line is a line break. I would appreciate if anyone has any advice. I have been using the Scanner class as below but am not sure how to even check if the line is a new line. Thanks
for (String fileName : f.list()) {
fileCount++;
Scanner sc = new Scanner(new File(f, fileName));
int count = 0;
String outputFileText = "";
//System.out.println(fileCount);
String text="";
while (sc.hasNext()) {
String line = sc.nextLine();
}
}
If you're just trying to read the file, I would suggesting using LineNumberReader instead.
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
String line = "";
while(line != null){
line = lnr.readLine();
if(line==null){break;}
/* do stuff */
}
Java's Scanner class already splits it into lines for you, even if the line is an empty String. You just have to scan through the lines again to get your values:
Scanner lineScanner;
while(sc.hasNext())
{
String nextInputLine = sc.nextLine();
lineScanner = new Scanner(nextInputLine);
while(lineScanner.hasNext())
{
//read the values
}
}
You probably want to use BufferedReader#readLine.

Categories