这样我的代码就完成了,但是现在无论选择的数字是否相等,我都需要打印出来!
我为“ FALSE /数字等于”创建了一个循环,但无法正常工作。
希望能对您有所帮助。
我的代码如下所示:
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
。
也许,您可能想比较数字对?或者,也许您想拥有一个包含已经看到的数字的数据结构(例如HashSet
或BitSet
)?
例如:当用户输入数字时,将其保存到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);