试图检索包含空格的String的最后一个字母

时间:2016-05-04 09:14:50

标签: java string substring whitespace

是的,所以我试图使用.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);}           
    }   
}

1 个答案:

答案 0 :(得分: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);}           
   }   
}