我必须获得字符串输入和整数输入,但输入顺序应该是整数先出现,然后应要求用户输入字符串
Scanner in = new Scanner(System.in);
input = in.nextLine();
k = in.nextInt();
in.close();
上面的代码工作正常,但是如果我像下面的代码一样首先输入一个整数
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
然后它抛出 java.lang.ArrayIndexOutOfBoundsException。
这是我的源文件的完整代码:
import java.util.Scanner;
公共类 StringSwap {
public static void main(String args[]) {
String input;
int k;
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
int noOfCh = noOfSwapCharacters(input);
originalString(input, noOfCh, k);
}
public static int noOfSwapCharacters(String s) {
char cS[] = s.toCharArray();
int i = 0, postCounter = 0;
while (cS[i] != '\0') {
if (cS[i] != '\0' && cS[i + 1] != '\0') {
cS[cS.length - 1 - postCounter] = '\0';
postCounter++;
}
i++;
}
return postCounter;
}
public static void originalString(String s, int noOfCh, int k) {
int counter = 1, chCounter = 0;
char cArray[] = s.toCharArray();
String post = "";
String pre = "";
String finalString = "";
char temp;
for (int i = 1; i <= k; i++) {
chCounter = 0;
counter = 1;
post = "";
pre = "";
for (int j = 0; j < cArray.length; j++) {
if (counter % 2 == 0 && chCounter <= noOfCh) {
temp = cArray[j];
post = temp + post;
cArray[j] = '\0';
chCounter++;
}
counter++;
}
for (int h = 0; h < cArray.length; h++) {
if (cArray[h] != '\0')
pre = pre + cArray[h];
}
finalString = pre + post;
for (int l = 0; l < finalString.length(); l++) {
cArray[l] = finalString.charAt(l);
}
}
System.out.println(finalString);
}
}
请指出我在这里做错了什么。
问题是'\n'
整数后面的字符。你打电话时nextInt
,扫描仪读取int
,但它不消耗'\n'
其后的字符;nextLine
这样做。这就是为什么你得到一个空行而不是你期望得到的字符串。
假设您的输入具有以下数据:
12345
hello
这是输入缓冲区最初的样子(^
代表的位置Scanner
读取下一条数据):
1 2 3 4 5 \n h e l l o \n
^
After nextInt
,缓冲区看起来像这样:
1 2 3 4 5 \n h e l l o \n
^
首先nextLine
消耗\n
,让你的缓冲区像这样:
1 2 3 4 5 \n h e l l o \n
^
Now the nextLine
调用将产生预期的结果。因此,要修复您的程序,您所需要做的就是添加另一个调用nextLine
after nextInt
,并丢弃其结果:
k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)