How do I recognize a line break with a switch case that evaluates a char in Java?

非 Y 不嫁゛ 提交于 2020-01-04 05:42:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!