gpt4 book ai didi

java - 用用户输入填充数组并使用 if 语句根据数组内的值进行算术运算

转载 作者:行者123 更新时间:2023-12-01 04:41:58 24 4
gpt4 key购买 nike

问题是:

编写一个Java程序,读取一系列正整数,并写出所有小于25的整数与所有大于或等于25的整数之和的乘积。使用0作为标记值。

我能够理解如何让用户将输入添加到数组中。但我找不到一种方法将代码与 if 语句集成以生成完整的工作程序来完成该任务。这是我目前的发现;

import java.util.*;
public class UserInput {
public static void main(String[] args) {

List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);

do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);

System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}

如何让数组读取输入并找到 25 以下所有数字与 25 以上所有数字之和的乘积。在这之间,什么是哨兵值以及知道它有什么用处?

解决方案:经过几个小时的调整下面志愿者发布的答案,我找到了一个适合我的解决方案。我特此发布,以防有​​人觉得有用;

import java.util.*;
public class UserInput {
public static void main(String[] args) {

List<Integer> list = new ArrayList<Integer>();
Scanner stdin = new Scanner(System.in);
do{
System.out.println("Current list is : " + list);
System.out.println("Enter number : ");
int entered = stdin.nextInt();
if(entered == 0){
int sum = 0,product = 1;
for(Integer number : list){
if(number<25){
sum += number;
}else if(number >= 25){
product *= number;
}
}
System.out.println("sum : " + sum);
System.out.println("product : " + product);
}else{
list.add(entered);
int sum = 0,product = 1;
for(Integer number : list){
if(number<25){
sum += number;
}else if(number >= 25){
product *= number;
}
}
System.out.println("sum : " + sum);
System.out.println("product : " + product);
}
System.out.println("Add more numbers to the list ? (Y/N) : ");

} while(stdin.next().equalsIgnoreCase("y"));
}
}

感谢大家的发帖和评论!这真的很有帮助! :)

最佳答案

Class Main {

public static void main(String[] args) {

List<Integer> numsGe25 = new ArrayList<>(); // Store numbers greather than or equal to 25

List<Integer> numsLt25 = new ArrayList<>(); // Store numbers less than 25


Scanner in = new Scanner(System.in);
int num = -1;
// Reads a number from the standard input till the 0 value is inserted. 0 is the sentinel
while ((num = in.nextInt()) != 0) {
if (num >= 25) {
numsGe25.add(num)
} else {
numsLt25.add(num);
}
}
System.out.println("sum of numbers >= 25: " + sum(numsGe25));
System.out.println("product of numbers < 25: " + product(numsLt25));
}

private static int sum(List<Integer> numbers) {
int result = 0;
for (Integer num : numbers) {
result += num;
}
return result;
}

private static int product(List<Integer> numbers) {
int result = 1;
for (Integer num : numbers) {
result *= num;
}
return result;
}
}

关于java - 用用户输入填充数组并使用 if 语句根据数组内的值进行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16386649/

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