gpt4 book ai didi

java - 为什么我会收到此错误?(双数组方法)

转载 作者:行者123 更新时间:2023-12-01 08:51:40 26 4
gpt4 key购买 nike

我收到错误

"Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at SearchArray.main(SearchArray.java:10)"

当我运行此代码时。谁能告诉我我做错了什么?

import java.util.Scanner;
public class SearchArray {
public static void main (String args[]){
//imput array size
//imput array digits
//imput element to search for

Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
double array[] = new double[size];

for(int i = 0; i <= array.length-1; i++){
array[i] = scan.nextDouble();
}

double digit = scan.nextDouble();
boolean bool = findElement(array,digit);

if(bool == true){
System.out.println(digit + " was found in the array");
}else if(bool == false){
System.out.println(digit + " was NOT found in the array");
}
}

public static boolean findElement(double[] array, double digit){
boolean bool = false;
//accepts double array, double & returns boolean
//check if numnber entered is in the array

for(int i = 0; i <= array.length-1; i++){
if(array[i] == digit){
bool = true;
}else{
bool = false;
}
}

return bool;
}
}

最佳答案

public class InputMismatchException Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

看看这个答案:https://stackoverflow.com/a/14027583/7421645并尝试理解为什么你会遇到异常,例如 try catch 异常:

try {
// ...
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //try to find out specific reason.
}

我还会尝试首先以 String 形式输入测试数据,至少直到您确定预期输入提供了预期输出为止。

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);

关于java - 为什么我会收到此错误?(双数组方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355211/

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