簡體   English   中英

在Ubuntu終端中工作的代碼,在Windows Eclipse中不工作

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

我正在嘗試使用useDelimiter解析"dd/mm/yyyy"類的日格式,但遇到一個奇怪的問題。 我使用了下面的代碼,該代碼在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);

但是在Windows上,當我將此代碼復制到Eclipse時,它在以下位置給出了錯誤:

int y = Integer.parseInt(year);

我發現了造成這種情況的原因。 當我打印“ year”時,它打印2014,但是2014年底有一些空格,因此整數不能正確解析。 我通過將Eclipse中的代碼更改為:

year = next().trim();

但是:

我的問題是,相同的代碼怎么可能在Ubuntu上而不在Windows平台上工作?

您也可以使用line.seperator。 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);


 }
}

嘗試將\\ r添加到定界符中。 在Ubuntu中,新行僅\\ n,而在Microsoft中新行為'\\ r \\ n'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM