gpt4 book ai didi

java - Java中调用后输入函数得到错误的值?

转载 作者:行者123 更新时间:2023-12-02 03:33:41 24 4
gpt4 key购买 nike

我有一个问题是,当我为数组 2d 输入值且值有效时,一切都已完成,但是当我为 TotalRow 或 TotalColumn 变量输入错误值时,我的输入函数迫使我输入 double 并在第二个中获取值。这是我的代码:

public static void input() {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Input total totalRow: ");
totalRow = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}

System.out.println("Input total totalColumn: ");
totalColumn = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}

// check case array must be square array
if (totalRow != totalColumn) {
System.out.println("Array must be square!");
input();
}
} catch (InputMismatchException e) {
// print message when user input other than integer
System.out.println("Please input an integer!");
input();
}

// initialize array with totalRow and totalColumn
array = new char[totalRow][totalColumn];

// input value for array
for (int i = 0; i < totalRow; i++) {
for (int j = 0; j < totalColumn; j++) {
array[i][j] = sc.next().charAt(0);
}
}
}

示例:我为totalRow和totalColumn输入2和a:出现消息,我重新输入是2和2,但我为数组输入了1 2 3 4 5 6 7 8,并且值从5获取。

最佳答案

这里有几件事导致您的代码失败:

  1. 错字:您正在检查totalRow <= 0两次(复制粘贴肯定错误)
  2. 如果条件不满足,则再次调用输入:这样做会递归实现该方法,这可能会导致序列的不期望的重复,让用户和开发人员发疯

  3. 您忘记了 Scanner.nextInt 不会消耗输入的最后一个换行符

我建议通过执行以下操作来修改代码:

if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
//input();
}

System.out.println("Input total totalColumn: ");
totalColumn = sc.nextInt();
sc.nextLine();
// verify value input must be a positive integer and greater than
// zero
if (totalColumn <= 0) {
System.out.println("......

关于java - Java中调用后输入函数得到错误的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716382/

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