问题
I have a switch case that evaluates each character from some input. The switch case evaluates spaces and tabs fine but when it goes to evaluate a line break I can't seem to find a case that it works with.
for (int i = 0; i < input.length(); i++) {
char curr = input.charAt(i);
switch (curr) {
case 'a':
//does stuff
break;
.
.
.
//space case
case ' ':
outputCode = outputCode + curr + " read \n";
break;
//tab case
case ' ':
outputCode = outputCode + curr + " read \n";
break;
//new line case, the issue
case '\n':
break;
default:
outputCode = outputCode + "Error Found at line " + LineNumber + curr + " is an Invalid Character.";
break;
回答1:
new line character will be platform dependent. You should probably use -
java.lang.System.lineSeparator()
for Java7+ OR
System.getProperty("line.seperator")
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
As you can see in case of windows it wont be a single char. Change your code accordingly.
回答2:
For Windows, the new line is \r\n
.
You would need to add another case for \r
to do nothing in order to ignore it.
回答3:
If it does not recognize \n
you can try \r\n
.
\r
for carriage return
Different Operating System may use different standard.
- If you are using Windows, try:
\r\n
- If you are using MAC OS X, try:
\n
- If you are using MAC OS 9 orprevious versions, try:
\r
- If you are using Unix:
\n
However, do note that \r\n
are actually 2 characters. So if you want to perform a switch with it, you may want to switch on a String
instead:
String ls= System.getProperty("line.separator");
switch (ls){
case "\n": System.out.println("Using Unix / Mac OSX");
break;
case "\r\n": System.out.println("Using Windows");
break;
case "\r": System.out.println("Using Mac OS 9 or previous");
break;
}
My output:
Using Windows
回答4:
You can borrow the approach form java.util.Scanner
class. Look at their LINE_SEPARATOR_PATTERN:
LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]";
来源:https://stackoverflow.com/questions/35569821/how-do-i-recognize-a-line-break-with-a-switch-case-that-evaluates-a-char-in-java