如何使循环仅返回当前项

时间:2014-08-05 12:58:34

标签: java loops

我正在java中构建一个单词益智游戏,它从数组中检索单词并隐藏一些字符供您猜测。从数组中重试单词,但使用scanner输入答案。程序有效。我想要做的是让循环只显示数组索引中的当前项而不显示列表中的先前项。

这是一个例子:
我不想要这个!!

一句话:戈夫***换货
回答:政府

字:po *** e 回答:警察

字:曲*** TY
回答:质量

...循环终止显示循环中的所有项目,就像正常循环一样

这就是我想要的!
字:po *** e 回答:警察

...循环只显示当前项目,同时期望输入下一个项目

这是我的整个代码:      import java.util.Scanner;       公共类WordPuzzleTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String [] arr= {"government",
                        "senate",
                        "president",
                        "minister",
                        "senator",
                        "parliament",
                        "legislature",
                        "judiciary",
                        "advisers",
                        "governor"};
        int index=0;
        String userInput;
        String newWord;
        int score=0;
        //double performance;
        int length=arr.length;

        WordPuzzle getInput=new WordPuzzle();

        System.out.println("--INSTRUCTION--");
            System.out.println("A Word will be given, you have to type the complete word");
            System.out.println("eg: ban***a");
            System.out.println("answer: bannana");
            System.out.println("--NOW BEGIN--");
            System.out.println("");

        while(index<arr.length){


            System.out.println("what is this word");

            //get the word from the array
            newWord=concealWord(arr[index]);
            System.out.println(newWord);
            userInput=getUserInput();

                if(userInput.equals(arr[index])){
                     System.out.println("correct!!!");
                     score++;
                }
                else{
                    System.out.println("Wrong!!!");
                }

                index++;
        }
        //calculate perforamance
         String star;
         if(score<=length/2){
              star="**2 stars";
            }
         else{
              star="***3 stars";
         }
          System.out.println("");
          System.out.println("--YOUR FINAL SCORE--");
          System.out.printf("Your score %d...\n(%s)",score,star);

    }
   // the getUserInput and concealWord methods

    public String getUserInput(){
    String answer;
    Scanner input= new Scanner(System.in);
    answer=input.next();
    return answer;
}

public String concealWord(String word){
    int wrdlength=word.length();

    int beginIndex=wrdlength/2-1;
    int endIndex=beginIndex+3;

    // get the substrings of the characters we want to replace
    String oldChar=word.substring(beginIndex, endIndex);
    String newChar="***";

    //replace the old characters with new ones
    String replacement=word.replace(oldChar, newChar);

    return replacement;

}

}

0 个答案:

没有答案