简体   繁体   English

在Ubuntu终端中工作的代码,在Windows Eclipse中不工作

[英]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. 我正在尝试使用useDelimiter解析"dd/mm/yyyy"类的日格式,但遇到一个奇怪的问题。 I used the code below, which works well on Ubuntu terminal. 我使用了下面的代码,该代码在Ubuntu终端上运行良好。

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 : 但是在Windows上,当我将此代码复制到Eclipse时,它在以下位置给出了错误:

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. 当我打印“ year”时,它打印2014,但是2014年底有一些空格,因此整数不能正确解析。 I solved this by changing the code in Eclipse to: 我通过将Eclipse中的代码更改为:

year = next().trim();

BUT : 但是:

My question is, how can it be possible that the same code works on Ubuntu but not on Windows platform ? 我的问题是,相同的代码怎么可能在Ubuntu上而不在Windows平台上工作?

You can also use a line.seperator. 您也可以使用line.seperator。 System.getProperty("line.separator") will retrieve a correct line separator that is used by your OS. System.getProperty(“ line.separator”)将检索您的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. 尝试将\\ r添加到定界符中。 In Ubuntu new line is only \\n while in Microsoft new line is '\\r\\n' 在Ubuntu中,新行仅\\ n,而在Microsoft中新行为'\\ r \\ n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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