编辑用户输入no。lexicograhical顺序的java代码。字
问题描述:
我正在尝试编写一个程序,要求用户在每行输入一个n
字,并将输出结果作为字典排序的字。编辑用户输入no。lexicograhical顺序的java代码。字
它要求用户输入第一行的字数,然后在每行输入一个字。我应该为这个程序使用一个多维数组。
我的代码可以正常工作,但它无法将n
字数作为用户输入的字数,而是仅占用n - 1
个字。
public static void main (String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String arr[] = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextLine();
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i].compareTo(arr[j])>0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < n; i++)
System.out.println(arr[i]);
}
答
您遇到的问题与扫描仪的nextInt()
方法有关。它只会只有从输入缓冲区中读取整数,并将换行符留在缓冲区中第一行的末尾。
这意味着,您在此之后第一次致电nextLine()
将读取一个空字符串并消耗换行符。
一个简单的解决方法是只需在input.nextInt()
和您的阅读循环之间拨打input.nextLine()
。
+0
对不起。我一开始并不能理解错误的根源,但是在重新阅读您的文章并在我的程序中实现它之后,我现在明白它是'nextInt()'创建一个空字符串并通过插入一个'nextLine()'在nextInt()之后和read-loop之前立即解决了空串问题。谢谢。 –
答
您可以简单地要求用户输入单词并让程序决定单词的数量。
Scanner input = new Scanner(System.in);
System.out.println("Enter words:");
String data = input.nextLine();
String[] arr= data.split("\\s+"); //splits the word by space and stores the words in pieces
// and then do the lexicographical operations here
请寄出你回来的错误,以及你试图解决的问题。干杯 – Alos
'nextLine()'在返回用户输入后自动下移。 –
@Niraj非常感谢你指出'nextLine()'这是我的程序错误的根源。用next()代替它解决了这个问题。然后,我可以输入所需的'n'个字作为用户输入。 –