如何在猪拉丁中设置循环?

时间:2015-11-23 06:08:11

标签: java while-loop

我写了一个简单的游戏猪拉丁,一切正常,但我想设置一个循环,当用户输入他的单词或短语和应用程序给他一个答案时,问题应该重复一次

我使用while

写了一个循环
while (true) {
if (input.equals("Exit")){
break;
} else {
// some actions 

但无论我把这段代码放在哪里,答案都是永远循环

我做错了什么?

这是我的代码:

import java.io.IOException;
import java.util.Scanner;

public class piglang {

    public static Scanner scanner = new Scanner(System.in);
    public static String input, output, line;
    public static char firstLetter;
    public static String vowels = "aeiouy";
    public static boolean capital = false;

    public static void main(String[] args) throws IOException{ 


          System.out.println("enter something: ");

          line = scanner.nextLine(); // scanner checks and returns the input that was skipped
          scanner = new Scanner(line); 

          while (scanner.hasNext()) { // check for other words in line

              input = scanner.next(); // finds and returns next complete token form this scanner          

              firstLetter = input.charAt(0);          

/*first if*/    if ('A' <= firstLetter && firstLetter <= 'Z') { // checking first letter
                    firstLetter = Character.toLowerCase(firstLetter);
                   capital = true;
                } else
                    capital = false;

/*second if*/   if (vowels != null) {  // checking if first letter is a vowelFGriopt;khtyl      mhp
                   output = (input + "ay"); 
                   } 
                else {  
                   if (capital) { // setting first letter to upperCase 
                      output = "" + Character.toUpperCase(input.charAt(1));  // char to String conversion
                      output = output + input.substring(2) + firstLetter + "ay";
                   } else {
                      output = input.substring(1) + firstLetter + "ay";
                   }
                }
                if (line.isEmpty()) {
                    output.isEmpty();
                }

                System.out.print(output + " ");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您只是将主要方法中的所有内容放在sortedKeys = sorted(newResults, key=lambda x: newResults[x]) 循环的块中,则必须进行的一项修改是在打印前初始化扫描仪&#34;输入一些东西&#34;。由于您重复使用相同的Scanner对象来解析该行,因此在下一次迭代中它不会引用System.in。您还需要检查while(true)而不是line.equals("Exit"),因为它确实input.equals("Exit")代表您的整个输入。我还建议您使用line而不是equalsIgnoreCase

equals

}