2016-04-29 71 views
1

下面是我在Java中遇到问题的一段代码;它似乎已经为另一个交易了一个问题。由于空白错误,我在检索用户输入时遇到问题;我通过添加“nextLine”而不是“next”来解决这个问题。在Java中第一次跳过控制台?

但是现在,它不会让用户有机会回答第一个问题,它会跳过控制台框并在继续问题2之前输出“错误”,现在用户的第一个控制台框显示出来。

我仔细检查:用“下一个”,第一个问题的控制台出现,但用“nextLine”,它跳过该控制台盒(不给用户输入任何东西的机会),吐出“错误”,然后进入问题二,用户终于可以输入内容。

它为什么这样做?

if(nwb.equalsIgnoreCase("numbers")){ 
    System.out.println("You must type in the rules verbatim "+ 
     "(word for word, including punctuation), "+ 
     "as shown on the Student Hand-Out. "+ 
     "Capitalization does not matter."); 
    int count = 1; 
    for(int i = 0; i<=(rules.length-1); i++){ 
     System.out.print("Rule #"+count); 
     String response = console.nextLine().replaceAll(" ",""); 
     if(response.replaceAll(" ", "").equalsIgnoreCase(rules[i].replaceAll(" ", ""))){ 
      System.out.println("CORRECT"); 
     }else{ 
      System.out.println("WRONG\nThe correct wording is: "+rules[i]); 
     } 
     count++; 
    } 
} 
+0

突出显示代码并按下ctrl + k。 – CConard96

+0

啊!这是如何完成的。谢谢,并对此表示歉意。 – Ray25Lee

+0

什么是规则? – Priyamal

回答

0

它有点繁琐的阅读您的代码,使用{}代码块格式化程序,以便更易于阅读。

尝试使用trim()函数删除输入前后的空格。

这可能是因为您已经在循环中初始化了您的响应字符串,请尝试将其移出并查看它做了什么。希望有帮助。

+0

这些建议更适合作为评论,而不是答案。我会建议删除你的答案,因为你可能会得票(但不是我) –

+0

我正在添加我的答案,我的不好,我不小心提交了它。 – Waker

+0

空白是问题吗?只有当我用“nextLine”替换“next”时才会显示错误。我不知道如何使用trim()(我对Java非常陌生),但我可以查看它。 – Ray25Lee

0
String response = console.nextLine(); 
    response = response.trim(); //remove spaces 
    if(response.equalsIgnoreCase(rules[i].trim())){ 
     System.out.println("CORRECT"); 
    }else{ 
     System.out.println("WRONG\nThe correct wording is: "+rules[i]); 
    } 

有几件事要解决。你正在取代空格。并在你的if循环中再次删除空格。并使用修剪()函数删除whitespaces.check与此示例

+0

我认为这里有一些空白编码的重复,但问题不在于空白;我已经解决了。问题是代码不允许用户在回答第二个问题之前回答第一个问题。我将它固定在你的例子中,它仍然在做这件事。 – Ray25Lee

0

对于谁可能关心,我做了一些搜索其他地方,并在几个小时后,我碰到的东西solved it;

基本上,我所做的就是这样的:

if(nwb.equalsIgnoreCase("numbers")){ 
        System.out.println("You must type in the rules verbatim (word for word, including puncutation), as shown on the Student Hand-Out. Capitalization does not matter."); 
        int count = 1; 
        for(int i = 0; i<=(rules.length-1); i++){ 
         System.out.print("Rule #"+count);        
         String derpTest = console.nextLine(); 
         String response = console.nextLine().replaceAll(" ",""); 
         if(response.equalsIgnoreCase(rules[i].replaceAll(" ",""))){ 
          System.out.println("CORRECT"); 
         }else{ 
          System.out.println("WRONG\nThe correct wording is: "+rules[i]); 
         } 
         count++; 
        } 
} 

弦乐derpTest用完了,从我所知道的,所以它的所有收益为String响应。我没有模糊的想法为什么这个工作;我不太明白这个链接是什么意思,所以,如果有人想要解释它,那真是太棒了。感谢所有试图解决这个问题的人,这是一个奇怪的问题。

+0

纠正;您需要将derpTest字符串放在循环的外部,或者当您继续讨论第2,3个问题时,它会再次变得奇怪。把它放在循环之外,出于某种原因,它一切正常。仍然不明白,但是,埃。随你。 – Ray25Lee