gpt4 book ai didi

java - 尝试按键退出时类型不匹配

转载 作者:行者123 更新时间:2023-12-01 17:01:53 25 4
gpt4 key购买 nike

我有以下 Java 程序。

package Arrays;

import java.util.Scanner;

public class Arrays {
public static void main(String[] args) {
final int size = 5; // Size of the input Array

Scanner input = new Scanner(System.in);
while (!input.equals("q")) {
System.out.println("Enter the 5 number you want to be stored in an array");

// get the input of array from the user
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}

/* Methods */
System.out.println("\n");
displayArray(a); // to display the numbers entered in Array
System.out.println("\n");
sumOfArray(a);// To print the sum of Array
System.out.println("\n");
productOfArray(a);// to print the product of Array
System.out.println("\n");
smallAndLargeOfArray(a);// to print the Max and Min number in Array
System.out.println("\n");
averageOfArray(a);// to print the average of Array
System.out.println("\n");
}
input.close();
}

private static void displayArray(int arr[]) {
System.out.print("The numbers you have inserted are ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) {
System.out.print(", ");
}
}

}

private static void sumOfArray(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.print("Sum of array is " + sum);

}

private static void productOfArray(int[] arr) {
int prod = 1;
for (int i = 0; i < arr.length; i++) {
prod *= arr[i];
}
System.out.print("Product of array is " + prod);
}

private static void smallAndLargeOfArray(int arr[]) {
int minimim = Integer.MAX_VALUE;
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (minimim > arr[i]) {
minimim = arr[i];
}
if (maximum < arr[i]) {
maximum = arr[i];
}
}
System.out.print("Minimum and Maximum numbers in array are " + minimim
+ " and " + maximum);

}

private static void averageOfArray(int arr[]) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double avg = sum / 5;
System.out.print("Average of array is " + avg);

}

}

这里我试图继续该程序直到用户输入 q ,但是当我输入 q 时它抛出以下错误。

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Arrays.Arrays.main(Arrays.java:16)

请让我知道我哪里出了问题以及如何解决这个问题。

谢谢

最佳答案

您应该这样做,因为您正在比较您的 Scanner 对象

String inputName=""
Scanner input = new Scanner(System.in);
inputName= in.nextLine();
while (!inputName.equals("q")) {..}

由于扫描仪对象不等于“q”(它是一个字符串),因此 while 循环连续运行。然后扫描仪等待一个整数,但它需要一个字符。所以扫描器抛出异常(说输入无法转换成整数值)

阅读:

关于java - 尝试按键退出时类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145624/

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