不能同时使用 Scanner.nextInt() 和 Scanner.nextLine()
2022-09-03 17:08:04
我必须得到一个字符串输入和一个整数输入,但是输入的顺序应该是整数先来,然后应该要求用户输入字符串
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);
}
}
请指出我在这里做错了什么。