-2

When the user enters 0, the program is supposed to stop. I can't figure out how to do this. For example: Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0 2 occurs 2 times 3 occurs 1 time 4 occurs 1 time 5 occurs 2 times 6 occurs 1 time 23 occurs 1 time 43 occurs 1 time

My code prints the 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")) ` after you get the input then nest inside that if all the code that should be executed should do the trick given what you said. – Falla Coulibaly Nov 02 '16 at 07:53
  • Hint: you want us to spend our time to help you. So you please spend the few minutes it takes to properly format/indent your source code; instead of dropping such a mess here - you see, that code doesn't even compile, as you have `if(!userInput.equals(0)){` there - missing the quotes around 0! – GhostCat Nov 02 '16 at 07:56

1 Answers1

0

You can do that by adding an else condition and using System.exit(0) and tell the user that the program is going to terminate.

static void exit(int status) Terminates the currently running program or Java Virtual Machine.

status 0 indicates that the program execution completed without exceptions.

You can look at the API here

Vasu
  • 21,832
  • 11
  • 51
  • 67