gpt4 book ai didi

java - 模式识别

转载 作者:行者123 更新时间:2023-12-02 08:02:07 26 4
gpt4 key购买 nike

所以我的代码已经完成,但现在我需要它来打印出所选数字是否相等!

我已经为 FALSE/NUMBERS ARE EQUAL 创建了一个循环,但它无法正常工作。希望你能帮忙。我的代码如下所示:

package patternrecognition;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

public class PatternRecognition {

public static void main(String[] args) throws Exception {



BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


int AntalNumre = -1;

boolean Gyldignummer = false;
while (Gyldignummer == false) {
System.out.print("\n\nIndtast antal numre: ");

String numre = reader.readLine().trim();

Gyldignummer = validInteger(numre);

if (Gyldignummer == false) {
System.out.println("Indtast et gyldigt nummer");
} else {

AntalNumre = Integer.parseInt(numre);
}

}


HashMap vaerdier = new HashMap();

for (int i = 0; i < AntalNumre; i++) { //Studerendes nummer(i+1)

boolean GyldigNummer2 = false;

while (GyldigNummer2 == false) {
System.out.print("\n\nIndtast en vaerdi for nummer " + (i + 1) + ": ");

String vaerdi = reader.readLine().trim();
int vaerdien = -1;

GyldigNummer2 = validInteger(vaerdi);
if (GyldigNummer2 == false) {
System.out.println("Indtast et gyldigt nummer");
} else {

vaerdien = Integer.parseInt(vaerdi);
}
vaerdier.put(vaerdi, new Integer(vaerdien));
}
}



TreeMap SorteretNummer = new TreeMap(vaerdier);

Iterator nr = SorteretNummer.keySet().iterator();

System.out.println("\n\n\n\n\n");
System.out.println("Numre valgt:");
System.out.println("------------");


while (nr.hasNext()) {

String navn = (String) nr.next();


int numre = ((Integer) SorteretNummer.get(navn)).intValue();

System.out.println("" + numre);

if (numre != numre) {
System.out.println("FALSE");
}
else {
System.out.println("ALLE THE NUMBERS ARE EQUAL");
}

}
}

public static boolean validInteger(String nummer) {
boolean validInteger = false;


try {
Integer.parseInt(nummer);
validInteger = true;
} catch (NumberFormatException nfe) {
validInteger = false;
}
return validInteger;

}
}

最佳答案

嗯,numre != numre必然是false当然除非numre碰巧在另一个线程中被更改(或者是 NaN ,但这是一个不同的故事)。

也许,您可能想比较数字对?或者,也许您想要一个数据结构来保存您已经见过的数字(例如 HashSetBitSet )?

示例:当用户输入数字时,将其保存到 HashSet<Integer> 。一旦完成,添加

Set<Integer> set = new hashSet<Integer>();

// ...as we're getting numbers from user

set.add(numre);

// ...

if (set.size() == 1)
System.out.println("OMG they're all the same! " + set);

关于java - 模式识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8748286/

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