I\'ve been working on a homework project here is the question: (Counting occurre
ID: 3629590 • Letter: I
Question
I've been working on a homework project here is the question:(Counting occurrence of numbers)
Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0.
I'm including my coding which is the following:
package Numbers;
import java.util.Scanner;
public class NewMain {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int[] count = new int [100];
int i = 0;
for (i=0; i<100; i++)
count [i] = 0;
System.out.println("Enter an integer between 1 - 100: ");
i = input.nextInt();
while (i!=0)
{
count[i]++;
i = input.nextInt();
}
for (i=0; i<100; i++){
if (count [i] !=0)
{
System.out.print(i+ " occurs " + count[i]+ " time");
if (count[i]>1)
{
System.out.println("s");
}
else
{
System.out.println("");
}
}
}
}
}
My question is someone mentioned that I should "j" as my variable and not "i".
I asked why, but the answer was not clear to me. The program seems to run fine, so can anyone clarify if I should use j or i as my variable?
Thanks!
Explanation / Answer
please rate - thanks
no reason at all to use j.
however you do have bugs.
ifyou think about it the array has 100 elements numbered 0 to 99, so when the number 100 is entered you want to increment count[99], when 1 is entered increment count[0], your not doing that. also the prompt should give the sentine
import java.util.Scanner;
public class main{
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int[] count = new int [100];
int i = 0;
for (i=0; i<100; i++)
count [i] = 0;
System.out.println("Enter an integer between 1 - 100 (0 to exit): ");
i = input.nextInt();
while (i!=0)
{
count[i-1]++;
System.out.println("Enter an integer between 1 - 100 (0 to exit): ");
i = input.nextInt();
}
for (i=0; i<100; i++){
if (count [i] !=0)
{
System.out.print((i+1)+ " occurs " + count[i]+ " time");
if (count[i]>1)
{
System.out.println("s");
}
else
{
System.out.println("");
}
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.