2014-11-14 179 views
-1

在我的代码结束时,用户选择重复。当它输出整个循环与原来的工作,而不是一个新的输入单词。例如,如果用户输入单词比萨。它会以我想要的方式完成循环。当我选择重复它时,循环会再次使用Pizza这个词,而不是要求我另外输入一个词。我的代码以我不想要的方式重复

do { 
if (answer == 1){ 
    System.out.println("Please enter another word:"); 
} 
    for (int i = 0; i < word.length(); i++) { 
    firstLetter = word.charAt(0); 
    word = word.substring(1, word.length()); 
    System.out.println(firstLetter + word); 
    word += firstLetter; 

} 
System.out.println("Would you like to Enter another word? If so, press 1. If not press 2."); 
answer = input.nextInt(); 
input.nextLine(); 
} 
    while(answer == 1); 
    System.out.println("Have a nice day!"); 
} 
} 

输出这个代码是: 比萨饼 izzap zzapi zapiz apizz 你想输入一个字?如果是,请按1.如果不是,请按2. 当我按1时,它会立即重复播放而不要求我提供新单词。我怎样才能得到想要的结果?

+1

**你在哪里**要求循环内的**字?我的意思是,你在哪里可以找到下一个单词?即'word = input.nextLine();'你是一个逻辑错误,你只需要遍历你的代码,通过逻辑思考就可以了。 – 2014-11-14 17:58:26

+0

在做其他事情之前,您应该询问输入,然后根据输入以某种方式进行。我认为,因为你在while循环结尾处要求输入,所以它会混淆逻辑。 – 2014-11-14 18:03:18

+0

这种缩进是不好的,它伤害了我的大脑。 – khelwood 2014-11-14 20:43:23

回答

2
System.out.println("Would you like to Enter another word? If so, press 1. If not press 2."); 
answer = input.nextInt(); 
input.nextLine(); 

我想如果你把最后一行将正常工作

更新

+0

@HovercraftFullOfEels tx,完成 – ControlAltDel 2014-11-17 15:30:04

1

也许是这样吧。你也错过了这个词的输入。你需要用户的单词和动作。

do { 
    System.out.println("1 for new word, 2 for exit"); 
    answer = input.nextInt(); 
    input.nextLine(); 
    System.out.println("input word"); 
    String word = input.nextLine(); 

    if (answer == 1){ 
     for (int i = 0; i < word.length(); i++) { 
      firstLetter = word.charAt(0); 
      word = word.substring(1, word.length()); 
      System.out.println(firstLetter + word); 
      word += firstLetter; 
     } 
    } 
} while(answer == 1); 
System.out.println("Have a nice day!"); 
+0

+1这是解决方案。该代码需要对'input.nextLine()'进行两次调用,一次只需吞服EOL,另一次调用下一个单词并将其放入'word'变量中。 – 2014-11-14 20:49:37

相关问题