There is a text that is like:
hi hi
hi hi
hi hi
The program is supposed to find 12 characters but it prints 14. I have found a different solution to my question but I didn't understand why this code doesn't work:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Learn {
public static void main(String[] args) throws FileNotFoundException {
// variables
String inName;
File input;
int counter;
String str;
// program code
// #1 How many characters
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the file name: ");
inName = scan.nextLine();
input = new File(inName);
scan.close();
scan = new Scanner(input);
scan.useDelimiter("");
counter = 0;
while (scan.hasNext()) {
str = scan.next();
if (!str.equals(" ") && !str.equals("\n"))
counter++;
}
System.out.println(counter);
}
}
It's prefer to use System.lineSeparator()
to declare the line separator because it's different in different os and check the empty string using .trim()
Update the condition to the following:
From:
if (!str.equals(" ") && !str.equals("\n"))
, To:
if (!"".equals(str.trim()) && !str.equals(System.lineSeparator()))
New lines can be represented using different Control characters \ Escape sequence. Your code doesn't work properly as it only takes \n
into account which denotes line feed. Carriage return is represented by \r
. You can fix your code by checking for carriage return as well by changing
if (.str.equals(" ") && !str.equals("\n") )
to
if (.str.equals(" ") &&.str.equals("\n") && !str.equals("\r") )
This way, you will be handling for both CR and LF control characters. If you are interested in learning more about this, check this Wikipedia article: https://en.wikipedia.org/wiki/Newline
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.