Arrays For循环和If Else语句的InputMismatchException问题
我是Java新手。如果你能帮我解决这个问题,我将不胜感激。 我试图制作一个程序来读取用户输入(整数),并将它们存储到数组中,然后打印出来。 我使用一个名为currentSize的变量来跟踪插入了多少个变量 由于我不知道将有多少个输入,每次元素数等于数组长度时,我使用array.copyOf方法将现有数组的大小加倍 我在.hasNextInt()中使用带有的while循环,目标是在用户输入其他内容(如字母而非整数)后退出while循环 我的问题是,它一直抛出InputMismatchException,尽管其想法是在输入非整数值后退出while循环 当我试图找出哪里出错时,我添加了2条print语句,以确保元素的数量正确计数,并且数组长度正在增加其大小Arrays For循环和If Else语句的InputMismatchException问题,arrays,for-loop,while-loop,user-input,inputmismatchexception,Arrays,For Loop,While Loop,User Input,Inputmismatchexception,我是Java新手。如果你能帮我解决这个问题,我将不胜感激。 我试图制作一个程序来读取用户输入(整数),并将它们存储到数组中,然后打印出来。 我使用一个名为currentSize的变量来跟踪插入了多少个变量 由于我不知道将有多少个输入,每次元素数等于数组长度时,我使用array.copyOf方法将现有数组的大小加倍 我在.hasNextInt()中使用带有的while循环,目标是在用户输入其他内容(如字母而非整数)后退出while循环 我的问题是,它一直抛出InputMismatchExcepti
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 + " ");
}
}
}
import java.util.Scanner;
导入java.util.array;
公共类阵列打印机{
公共静态int默认_长度=2;
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
//跟踪我们插入了多少元素
int currentSize=0;
int[]numList=新int[默认长度];
System.out.println(“请在数组中插入要存储的值:”);
while(在.hasNextInt()中){
for(int i=0;i
这可能只是一件非常简单的事情,但我已经浏览了Stack上的所有其他帖子,但都没有用
非常感谢你 您的算法有问题。包含以下内容的行:
while(在.hasNextInt()中)
将只运行一次,
在第一次输入之前。在此之后,(inti=0;i将无限期运行,或者直到键入无效的整数
为了理解这个问题,您需要仔细查看异常发生的那一行:numList[i]=In.nextInt()代码>。.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 + " ");
}
for(int i=0;i
我知道你是在玩循环和数组来学习它。然而,要实现这一逻辑
以更简单的方式,您应该使用列表。A(即:)可以自动处理不同数量的项目,您的最终代码会简单得多。非常感谢您!我知道dang for循环有问题,因为我一尝试使用它,问题就出现了。现在我意识到in.hasNextInt只运行您指出的一个。