gpt4 book ai didi

java - 如何接受和输出数组中的 double 和整数?

转载 作者:行者123 更新时间:2023-11-30 02:38:44 26 4
gpt4 key购买 nike

import java.util.Scanner;

public class PeopleWeights {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

final int NUM_VALS = 5;

int [] personsWeight = new int[NUM_VALS];

int i = 0;

for (i = 0; i < NUM_VALS; ++i) {
System.out.print("Enter weight " + (i + 1) + ": ");
System.out.println();
personsWeight[i] = scnr.nextInt();
}

double sumVal = 0.0;

for (i = 0; i < NUM_VALS; ++i) {
sumVal = sumVal + personsWeight[i];
}

double avgVal = 0.0;

for (i = 0; i < NUM_VALS; ++i) {
avgVal = sumVal / NUM_VALS;
}

double maxVal = 0.0;

for (i = 0; i < NUM_VALS; ++i) {
maxVal = personsWeight[0];
if (maxVal < personsWeight[i]) {
maxVal = personsWeight[i];
}
}

System.out.println();
System.out.println(personsWeight[1] + " " + personsWeight[2] + " "
+ personsWeight[3] + " " + personsWeight[4] + " " + personsWeight[5]);
//I know that this can be cleaner but this is where the
//problem occurs with a InputMismatchException.
//I know it's caused by the double being introduced
//but don't know how to fix it.


System.out.println("Total weight: " + sumVal);

System.out.println("Average weight: " + avgVal);

System.out.println("Max weight: " + maxVal);

return;
}
}

输入如下:
236,
89.5 ,
142,
166.3 ,
93 .

我想像输入一样处理输出数字。双倍或整数。

无论如何我可以让阵列在扫描仪中接受这两种类型的数字,还是我必须采用另一种工作方式?

最佳答案

您可以使用 hasNextInt() 初步确定输入的数字是 Double 还是 Integer或 hasNextDouble() Scanner的方法类(class)。

if (scnr.hasNextInt()) {
int n = scnr.nextInt();
//your code to handle `integer` case
}
else if(scnr.hasNextDouble()) {
double d = scnr.nextDouble();
//your code to handle `double` case
}

仅供引用,您也可以将所有内容保留为 double .它将同时处理 int s 和 double s 并将执行而不会出现任何错误。

关于java - 如何接受和输出数组中的 double 和整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42383572/

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