For 循环和 If Else 语句的 InputMismatchException 问题

Java学习者

我是 Java 新手。如果您能帮我解决这个问题,我将不胜感激。我正在尝试制作一个程序来读取用户输入(整数)并将它们存储到一个数组中,然后将它们打印出来。我使用一个名为currentSize的变量来跟踪插入了多少变量。

由于我不知道将有多少个输入,每次元素编号等于数组长度时,我使用Arrays.copyOf方法将现有数组的大小加倍。

我使用带有in.hasNextInt()的 while 循环,目的是在用户输入其他内容(例如字母而不是整数时退出 while 循环。

我的问题是它不断抛出 InputMismatchException 虽然想法是一旦输入非整数值就退出 while 循环。

当我试图查明出错的地方时,我添加了 2 个打印语句以确保元素数量正确计数并且数组长度正在增加其大小。

System.out.println("No of elements: " + currentSize);
System.out.println("Array size: " + numList.length);

我尝试了另一种方法,并让它在没有for循环的情况下以我想要的方式工作,所以我怀疑 while 循环是问题所在。

import java.util.Scanner;
import java.util.Arrays;

public class ArrayPrinter{
    public static int DEFAULT_LENGTH = 2;
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        //keep track of how many element we insert
        int currentSize = 0;
        int[] numList = new int[DEFAULT_LENGTH];

        System.out.println("Please insert value to store in array: ");
        while(in.hasNextInt()){
            for(int i = 0; i < numList.length; i++){
                numList[i] = in.nextInt();
                currentSize++;
                System.out.println("No of elements: " + currentSize);
                System.out.println("Array size: " + numList.length);
                if(currentSize == numList.length){
                    numList = Arrays.copyOf(numList, currentSize * 2);
                }       
            }
        }
        for(int number : numList){
            System.out.print(number + " ");
        }
    }
}

这可能只是一些非常简单的事情,但我已经浏览了 Stack 上的所有其他帖子,但无济于事。

太感谢了!

莱昂纳多·克鲁兹

你的算法有问题。包含:的while(in.hasNextInt())行将只运行一次,在第一个输入之前。之后,您的第二个循环for(int i = 0; i < numList.length; i++)将无限期运行或直到您输入无效整数。

为了理解问题,您需要准确查看发生异常的行:numList[i] = in.nextInt();. 该方法in.nextInt无法处理无效输入。

您只需要“for”循环,并且需要在其中使用hasNextInt

for (int i = 0; i < numList.length; i++) {
    if (in.hasNextInt()) {
        numList[i] = in.nextInt();
        currentSize++;
        System.out.println("No of elements: " + currentSize);
        System.out.println("Array size: " + numList.length);
        if (currentSize == numList.length) {
            numList = Arrays.copyOf(numList, currentSize * 2);
        }
    }
}

for (int number : numList) {
    System.out.print(number + " ");
}

我知道您正在使用循环和数组来学习它。但是,要以更简单的方式实现此逻辑,您应该使用 List。一个列表(即:ArrayList中)可以自动处理可变数量的项目和您的最终代码就会简单得多。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章