2014-10-28 101 views
-1

我现在需要让我的程序输出这样的:正确while循环输出(爪哇)

输入一个单词:房子
你想要什么字母代替?:一个
有一个在房子里没有一个。
你想要替换什么字母?:b
没有内部。
你想替换什么字母?:e
你想用什么字母来代替它? w
新单词是housw。
_____________________________________。

这里是我的电流输出:

输入一个单词:房子
你想要什么字母代替?:一个
有一个在房子里没有一个
什么信你要替换?: b
你想用什么字母来代替它?

_____________________________________。

我遇到了麻烦,我的while循环。而我不知道如何纠正错误。这里是我的代码:

import java.util.Scanner; 
public class WordScrambler { 

    //name 

    public static void main(String[] args) { 

     String word = ""; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Enter a word: " + word); 
     word = keyboard.nextLine(); 


     String readChar = null; 
     System.out.print("What letter do you want to replace?: "); 
     readChar = keyboard.next(); 

     while(true) 
     { 
      if(word.contains(readChar)) 
      { 
       String changeChar; 
       System.out.print("With what letter do you wish to replace it? "); 
       changeChar = keyboard.next(); 

       System.out.println(word.replace(readChar, changeChar)); 

      } 
      else 
      { 
       System.out.print("There is no "+ readChar + " in " + word); 
       System.out.println(); 
       System.out.print("What letter do you want to replace?: "); 
       readChar = keyboard.next(); 
       String changeChar; 
       System.out.print("With what letter do you wish to replace it? "); 
       changeChar = keyboard.next(); 
       System.out.println(word.replace(readChar, changeChar)); 
      } 
     } 
    } 
} 
+0

我们没有为你做功课。询问一个合适的问题。 – VeenarM 2014-10-28 21:19:06

+0

你得到了什么错误。请问一个具体的问题 – Chiseled 2014-10-28 21:20:19

+0

这不是while循环的问题。你可以标题你的问题有关吗? – khelwood 2014-10-28 21:20:28

回答

0

如果您在

else部分看,你可以清楚地看到,你问他有什么愿望函,以取代原信用户,而不是简单地说,这个词不包含字母。

您可以通过简单地从您的else语句中删除两个“问题”部分来解决此问题。

零部件删除:

System.out.print("What letter do you want to replace?: "); 
    readChar = keyboard.next(); 
    String changeChar; 
    System.out.print("With what letter do you wish to replace it? "); 
    changeChar = keyboard.next(); 
    System.out.println(word.replace(readChar, changeChar)); 
+0

当我在代码中删除这部分时,“没有内部”变成了一个永无止境的循环。 @ Code0 – Alex 2014-10-28 21:31:44

+0

是的,因为你再也不要求再输入一次(scanner.next()阻止主线程在主线程上运行)。只需申请一个新的输入,然后设置好。 @Alex – Code0 2014-10-28 21:37:08

+0

谢谢! @ Code0 – Alex 2014-10-28 21:46:53

1

在你else语句一旦一个人进入,这并不存在,你告诉他们,让他们选择一个新字符的字符,但你甚至不检查,如果这种新的性格中存在字符串,而是直接问他们你想用什么字符替换它。 你else语句应该是这样的:

else{ 
     System.out.print("There is no "+ readChar + " in " + word); 
     System.out.print("What letter do you want to replace?: "); 
     readChar = keyboard.next(); 
    } 

这意味着你的循环将再次运行,如果信存在验证。

0

问题出在你的其他块语句的顺序排列。如果你有一个调试器,请尝试调试你的例子(一步一步通过你的程序 - 你会看到问题)。如果您没有调试器,请尝试更改system.out.println()显示的文本。只需在每个system.out.println()语句中添加一些独特的文本,以便它们可以为您区分。问题不远处...

祝你好运!