gpt4 book ai didi

java - 当用户输入 yes 时继续程序

转载 作者:太空宇宙 更新时间:2023-11-04 14:06:15 26 4
gpt4 key购买 nike

好吧,我的程序工作正常,但最后它会询问用户是否愿意输入另一组整数,如果他们输入“yes”,则该过程将重新开始。我的程序正在重新开始,但它保留所有相同的用户输入,因此它只是不断重复原始输入的相同输出。

这是我的代码

import java.util.Scanner;

public class PositiveNegative {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Input a list of integers (end with 0): ");
int nums = input.nextInt();

String answer;
int pos = 0;
int neg = 0;
int total = 0;
int count = 0;
double avg = 0;

do {
while (nums != 0) {
if (nums >= 1) {
pos++;
} else {
neg++;
}
total = total + nums;
count++;

avg = total * 1.0 / count;

System.out.print("Input a list of integers (End with 0): ");
nums = input.nextInt();
}
System.out.print("# of positives are: " + pos + "\n" + "# of negatives are : " + neg + "\n" + "The total: " + total + "\n" + "The average: " + avg);
System.out.print("\nWould you like to continue with new inputs? ");
answer = input.next();
} while (answer.equalsIgnoreCase("Yes"));
}
}

我当前的输出如下所示:

Input a list of integers (end with 0): 1

Input a list of integers (End with 0): 2

Input a list of integers (End with 0): -1

Input a list of integers (End with 0): 3

Input a list of integers (End with 0): 0

number of positives are: 3

number of negatives are : 1

The total: 5

The average: 1.25

Would you like to continue with new inputs? yes

number of positives are: 3

number of negatives are : 1

The total: 5

The average: 1.25

Would you like to continue with new inputs?

它应该看起来像这样:

number of positive inputs: 3

number of negative inputs: 1

The total: 5.0

The average: 1.25

Would you like to continue with new inputs? yes

Input a list of integers (end with 0): 0

No numbers were entered except 0

Would you like to continue with new inputs? no

最佳答案

这样做

import java.util.Scanner;

public class PositiveNegative {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

String answer;
do {
System.out.print("Input a list of integers (end with 0): ");
int nums = input.nextInt();

int pos = 0;
int neg = 0;
int total = 0;
int count = 0;
double avg = 0;

while (nums != 0) {
if (nums >= 1) {
pos++;
} else {
neg++;
}
total = total + nums;
count++;

avg = total * 1.0 / count;

System.out.print("Input a list of integers (End with 0): ");
nums = input.nextInt();
}

if(count == 0) {
System.out.print("No numbers were entered except 0");
} else {
System.out.print("# of positives are: " + pos + "\n" + "# of negatives are : " + neg + "\n" + "The total: " + total + "\n" + "The average: " + avg);
}
System.out.print("\nWould you like to continue with new inputs? ");
answer = input.next();
} while (answer.equalsIgnoreCase("Yes"));
}
}

关于java - 当用户输入 yes 时继续程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28842809/

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