gpt4 book ai didi

java - 不能同时使用 Scanner.nextInt() 和 Scanner.nextLine()

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:32 25 4
gpt4 key购买 nike

<分区>

我必须得到一个字符串输入和一个整数输入,但是输入的顺序应该是整数在前,然后应该要求用户输入字符串

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;

公共(public)类 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);
}

请指出我在这里做错了什么。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com