gpt4 book ai didi

java - 寻找唯一的数字

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

我正在尝试使用一组来查找唯一数字并从用户输入的数字中获取总和。我听说数组更容易,但一组可能适合我。我对集合或它们的作用不太了解,所以任何输入都会很棒。非常感谢大家!

import java.util.Scanner;

public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);

public double go()
{
double a = 0
counter = 10;

int total = 0;

for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}

System.out.println("the total is ";
return a;
}
}

最佳答案

java.util.HashSet 存储唯一值。对程序进行了细微更改,以使用 Set 存储唯一值并使用 for 循环计算唯一值的总和

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);

public int go() {
int a = 0;
int n = 0;
counter = 10;

Set<Integer> unValues = new HashSet<Integer>();

while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}

int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}

System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}

public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}

关于java - 寻找唯一的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43196847/

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