当用户输入0时,程序应该停止。我无法弄清楚如何做到这一点。例如: 输入1到100之间的整数:2 5 6 5 4 3 23 43 2 0 2发生2次 3发生1次 4发生1次 5次发生2次 6次发生1次 23次发生1次 43次出现
我的代码打印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]+ " ");
}
}
}
答案 0 :(得分:0)
您可以通过添加else
条件并使用System.exit(0)
来告诉用户程序将要终止。
static void exit(int status)终止当前正在运行的程序或Java虚拟机。
状态0表示程序执行完成,没有异常。
您可以查看API here