该程序应该采用用户输入的句子,例如“我很饿”,然后要求旋转多个单词。如果数字是2,则新的输出将是“我非常饿”。到目前为止,这是我的代码,但似乎有错误。当我运行代码时,将出现:java.util.InputMismatchException。下面还有一些其他信息,但我不确定这意味着什么。到目前为止,这是我的代码。
import java.util.*;
public class WordRotation
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence");
if(input.hasNext());
{
String s = input.next();
String[] words = s.split(" ");
System.out.println("Enter number of words to be rotated");
int rotation = input.nextInt();
for (int i = 0;i < words.length;i++)
{
System.out.print(words[(i + words.length - rotation)%words.length] + " ");
}
}
}
}
我试图将我的if语句更改为while语句,但是代码从不输出任何东西,它只是不断加载。
最佳答案
将String s = input.next();
更改为String s = input.nextLine();
是的,这实际上是一种解决方案,因为在我们按下Enter键之后,在我们按下\n
之后,还有一个Enter
仍然留在流中,并且.nextInt()
读取了\n
和您的电话号码。如果使用input.nextLine()
而不是input.next()
,我们将捕获\n
,并且input.nextInt()
将读取下一个不带\n
的整数。
有更多信息https://stackoverflow.com/a/7056782/1366360