Ttrying循环直到用户输入“停止”

时间:2015-04-25 13:05:06

标签: java

我尝试执行一个循环来读取和处理句子,并且仅在用户键入“停止”以结束程序时结束。下面是使用的代码,我不断收到编译错误else if

System.out.println("Please Input a sentence and (terminate with \"STOP \")"); 

    String sentenceInput; 
    int sentenceLength; 
    char sentencePunct; 
    int divisionNum; 
    int number; 
    int divided; 
    int remainder; 

    sentenceInput= myScanner.nextLine(); 
    sentenceLength = sentenceInput.length(); 
    remainder = sentenceLength%2; 
    sentencePunct = sentenceInput.charAt(sentenceLength -1); 

    while (!sentenceInput.equals ("STOP")) {
        if (sentencePunct == '?') 
        { 
            if (remainder == 0) 
                System.out.println("Yes");`
                System.out.println("Please Input another sentence (terminate with \"STOP \")");
                sentenceInput= myScanner.nextLine(); 
            else 
                System.out.println("No");
                System.out.println("Please Input another sentence (terminate with \"STOP \")");
                sentenceInput= myScanner.nextLine(); 
        } 
        else if (sentencePunct == '!') 
                System.out.println("Wow!");
                System.out.println("Please Input another sentence (terminate with \"STOP \")");
                sentenceInput= myScanner.nextLine(); 
            else 
                System.out.println("You always say " + sentenceInput);
                System.out.println("Please Input another sentence (terminate with \"STOP \")");
                sentenceInput= myScanner.nextLine(); 
        }   

}

2 个答案:

答案 0 :(得分:2)

你的范围已被搞砸了,需要确保完整的if / else附在{}中,因为你的大多数其他人都没有任何东西可以连接。

    while (!sentenceInput.equals ("STOP")) {
    if (sentencePunct == '?') 
    { 
        if (remainder == 0) {
            System.out.println("Yes");`
            System.out.println("Please Input another sentence (terminate with \"STOP \")");
            sentenceInput= myScanner.nextLine(); 
        }
        else {
            System.out.println("No");
            System.out.println("Please Input another sentence (terminate with \"STOP \")");
            sentenceInput= myScanner.nextLine(); 
        }
    } 
    else if (sentencePunct == '!') {
            System.out.println("Wow!");
            System.out.println("Please Input another sentence (terminate with \"STOP \")");
            sentenceInput= myScanner.nextLine(); 
        }
        else {
            System.out.println("You always say " + sentenceInput);
            System.out.println("Please Input another sentence (terminate with \"STOP \")");
            sentenceInput= myScanner.nextLine(); 
        }
    }   

}

答案 1 :(得分:1)

你需要在else中定义语句的范围(多个语句)if和else部分你可以用大括号。所以你的代码应该是:

else if (sentencePunct == '!')  {
    ....
} else {
    ...
} 

如果你没有定义范围,那么编译器只考虑if / else / else之后的立即声明,如果在范围内,在你的情况下,它将无法找到将(最后)与其关联的那个。