Wenn der Benutzer 0 eingibt, soll das Programm stoppen. Ich kann nicht herausfinden, wie das geht. Zum Beispiel: die ganzen Zahlen eingeben zwischen 1 und 100: 2 5 6 5 4 3 23 43 2 0 2 tritt 2mal 3 tritt 1mal 4 tritt 1mal 5 tritt 2mal 6 tritt 1mal 23 auftritt 1 Mal 43 tritt 1malWie füge ich meinem Code einen Sentinel-Wert hinzu?
Mein Code der 0.
public class CountOccurrences {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter ten integers between 1 and 100: ");
String userInput = input.nextLine();
//this splits the user input into an array using a space
String[] inputString = userInput.split(" ");
String[] previousValues = new String[inputString.length];
int count = 1;
//Compare elements and update count for new string
for (int i = 0; i < inputString.length; i++) {
for (int j = i+ 1; j < inputString.length; j++) {
if (inputString[i].equals(inputString[j]) && notFound (previousValues, inputString[i]) { `
count++;
}
}
//Prints only unique strings
if(!userInput.equals("0")){
if (notFound(previousValues,inputString[i])) {
if (count>1) {
System.out.println(inputString[i] + " occurs " + count + " times");
} else {
System.out.println(inputString[i] + " occurs " + count + " time");
}
count = 1;
}
if (notFound(previousValues,inputString[i])) {
previousValues[i] = inputString[i];
}
}}
}
//This method returns a boolean value. It is true if the string is not in the array and vice versa
public static boolean notFound(String[] pastValues, String currentString) {
boolean valueNotFound = true;
int index = 0;
while(index < pastValues.length && valueNotFound) {
if ((pastValues!= null) &&(currentString.equals(pastValues[index]))) {
valueNotFound = false;
}
index++;
}
return valueNotFound;
}
//Method for printing an array
public static void printArray(String [] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+ " ");
}
}
}
'if (! Userinput .equals („0“))', nachdem Sie die Eingabe dann Nest im Inneren, dass, wenn alle der Code, der ausgeführt werden soll, sollte den Trick gegeben tun was hast du gesagt. –
Hinweis: Sie möchten, dass wir unsere Zeit verbringen, um Ihnen zu helfen. Bitte verbringen Sie also die paar Minuten, um Ihren Quellcode richtig zu formatieren/einzuteilen. Anstatt hier eine solche Unordnung zu verwerfen - ihr seht, dass dieser Code nicht einmal kompiliert, wie Sie es haben, wenn (! userInput.equals (0)) {'da - die Anführungszeichen um 0 fehlen! – GhostCat