The program below reads the integers between 1 and 100 and counts the occurrences of each. The input ends with 0. Here is a sample run of the program:
Enter the integers between 1 and 100: <2, 5, 6, 5, 4, 3, 23, 43, 2, 0 is entered>
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
Issue:
However, if the integer entered is <1, 0 is entered>, then the output is:
1 occurs 0 time.
which is wrong, the correct output should be:
1 occurs 1 time.
Requirement:
Debug the program and fix this error. Show this to the trainer.
Program:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/ Code (Java)
package occurence;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Occurence {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String sNumbers = "";
int iNum = 0
,iElementCount = 0 // number of elements
,iOccurence = 0; // How many times the number occurs
String sNum = JOptionPane.showInputDialog("Enter an Integer: ");
iNum = Integer.parseInt(sNum); //Converts string to integer
//Valid numbers
while(!(iNum == 0)) // iNum not equal to zero
{
if ((iNum>=1)&&(iNum<=100))
{
sNumbers = sNumbers + iNum + ",";
iElementCount++;
sNum = JOptionPane.showInputDialog("Enter another Integer: ");
iNum = Integer.parseInt(sNum); //Converts string to integer
}
else if ((iNum<0)||(iNum>100))
{
sNum = JOptionPane.showInputDialog("Invalid Number. Enter another Integer: ");
iNum = Integer.parseInt(sNum); //Converts string to integer
}
}
//zero
if(iNum==0)
{
// if integer is between 1 to 100
String[] sArray = new String[iElementCount];
sArray = sNumbers.split(",");
Arrays.sort(sArray);
for(int index = 0; index<sArray.length; index++)
{
if(index == sArray.length-1)
{
//last index
if(iOccurence > 1)
{
System.out.println(sArray[index]+" occurs "+iOccurence+" times.");
}
else
{
System.out.println(sArray[index]+" occurs "+iOccurence+" time.");
}
iOccurence = 1;
}
else
{
//not the last index
if(sArray[index].equals(sArray[index+1]))
{
if(iOccurence==0)
{
iOccurence = iOccurence + 2;
}
else
{
iOccurence++;
}
}
else
{
if(iOccurence > 1)
{
System.out.println(sArray[index]+" occurs "+iOccurence+" times.");
}
else
{
System.out.println(sArray[index]+" occurs "+iOccurence+" time.");
}
iOccurence = 1;
}
}
} //for loop
}
}
}