简体   繁体   中英

working code in Ubuntu terminal, doesn't work in Windows Eclipse

I'm trying to parse day format like "dd/mm/yyyy" with useDelimiter but faced a strange problem. I used the code below, which works well on Ubuntu terminal.

Scanner k = new Scanner(System.in);
k.useDelimiter("/|\n");
String day,month,year;
day = k.next(); month = k.next(); year = next();
System.out.println(day + "/" + month + "/" + year);
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);

But on Windows when I copy this code to Eclipse, it gives an error at :

int y = Integer.parseInt(year);

I've found what causes this. When i print "year", it prints 2014 but there is some whitespace at the end of 2014 so the integer isn't parsed correctly. I solved this by changing the code in Eclipse to:

year = next().trim();

BUT :

My question is, how can it be possible that the same code works on Ubuntu but not on Windows platform ?

You can also use a line.seperator. System.getProperty("line.separator") will retrieve a correct line separator that is used by your OS.

public class Tester {


 public static void main(String[] args) {
    Scanner k = new Scanner(System.in);
    String newLine = System.getProperty("line.separator");

    k.useDelimiter("/|"+newLine);
    String day,month,year;

    day = k.next(); 
    month = k.next(); 
    year = k.next();
    System.out.println(day + "/" + month + "/" + year);


 }
}

Try adding \\r to the delimiters. In Ubuntu new line is only \\n while in Microsoft new line is '\\r\\n'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM