2016-05-04 60 views
0

對,所以我有點卡住試圖檢索使用.substring的最後一個字母。如果我輸入例如「100C」,它將正常工作,變量celOrFar將=「C」。但是,用戶應該在數字後插入一個空格,但這樣做會給我一個不正確的結果。 「100 C」會給我「0」而不是C,「1234 5678C」會給我4!我仍然是Java的初學者,所以任何幫助表示讚賞!試圖檢索包含空格的字符串的最後一個字母

public static void stateOfWater() {  

    System.out.println("Enter a temperature followed by a space and C/F: "); 
    String userInput = input.next(); 
    String celOrFar = userInput.substring(userInput.length()-1); 

    String degreeString = userInput.trim(); 
    degreeString = degreeString.replace("C", ""); 
    degreeString = degreeString.replace("F", ""); 
    degreeString = degreeString.replace("f", ""); 
    degreeString = degreeString.replace("c", ""); 

    int degree = Integer.parseInt(degreeString);  

    if (celOrFar.equals("C")|| celOrFar.equals("c")) {   
     if (degree <= 0) {System.out.println("Your water is a solid at " +userInput);}   
     if (degree >= 100) {System.out.println("Your water is a gas at " +userInput);}  
     if (degree >0 && degree <100) {System.out.println("Your water is a liquid at " +userInput);}    
    } 

    if (celOrFar.equals("F") || celOrFar.equals("f")) {   
     if (degree <= 32) {System.out.println("Your water is a solid at " +userInput);}   
     if (degree >= 212) {System.out.println("Your water is a gas at " +userInput);}   
     if (degree >32 && degree <212) {System.out.println("Your water is a liquid at " +userInput);}   
    } 
} 
+0

掃描器使用空格作爲分隔符,您應該閱讀[doc](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) –

回答

0

scanner.next讀字符,直到它遇到一個空格。如果你想閱讀包括空格在內的完整行,那麼你需要使用nextLine。見下文。

public static void stateOfWater() {  

System.out.println("Enter a temperature followed by a space and C/F: "); 
String userInput = input.nextLine(); // this will read the complete line including spaces. 
String celOrFar = userInput.substring(userInput.length()-1); 

String degreeString = userInput.trim(); 
degreeString = degreeString.replace("C", ""); 
degreeString = degreeString.replace("F", ""); 
degreeString = degreeString.replace("f", ""); 
degreeString = degreeString.replace("c", ""); 

int degree = Integer.parseInt(degreeString);  

if (celOrFar.equals("C")|| celOrFar.equals("c")) {   
    if (degree <= 0) {System.out.println("Your water is a solid at " +userInput);}   
    if (degree >= 100) {System.out.println("Your water is a gas at " +userInput);}  
    if (degree >0 && degree <100) {System.out.println("Your water is a liquid at " +userInput);}    
} 

if (celOrFar.equals("F") || celOrFar.equals("f")) {   
    if (degree <= 32) {System.out.println("Your water is a solid at " +userInput);}   
    if (degree >= 212) {System.out.println("Your water is a gas at " +userInput);}   
    if (degree >32 && degree <212) {System.out.println("Your water is a liquid at " +userInput);}   
    } 
} 
相關問題