Need help finding error in code to Java Ex. 7.7: public class HW7_07 { public st
ID: 3691582 • Letter: N
Question
Need help finding error in code to Java Ex. 7.7:
public class HW7_07 {
public static void main(String[] args) {
int[] randomNum = new int[10];
for (int i = 0; i < 100; i++) {
}
for (int i = 0; i < randomNum.length; i++) {
System.out.println("The number " + i + " occurs " + randomNum[i] + " times.");
}
}
public static int getRandomInt(int lowerBound, int upperBound) {
lowerBound = 0;
upperBound = 9;
int random = (int) (Math.random() * 9 + 1);
return random;
}
}
CURRENT OUTPUT:
The number 0 occurs 0 times.
The number 1 occurs 0 times.
The number 2 occurs 0 times.
The number 3 occurs 0 times.
The number 4 occurs 0 times.
The number 5 occurs 0 times.
The number 6 occurs 0 times.
The number 7 occurs 0 times.
The number 8 occurs 0 times.
The number 9 occurs 0 times.
Explanation / Answer
Hi, Below Highlighted line is the error.
HW7_07.java
public class HW7_07 {
public static void main(String[] args) {
int[] randomNum = new int[10];
//for (int i = 0; i < 100; i++) {
for (int i = 0; i < 10; i++) {
randomNum[i] = getRandomInt(0, 9);
}
for (int i = 0; i < randomNum.length; i++) {
System.out.println("The number " + i + " occurs " + randomNum[i] + " times.");
}
}
public static int getRandomInt(int lowerBound, int upperBound) {
lowerBound = 0;
upperBound = 9;
int random = (int) (Math.random() * 9+1);
return random;
}
}
output:
The number 0 occurs 6 times.
The number 1 occurs 6 times.
The number 2 occurs 2 times.
The number 3 occurs 4 times.
The number 4 occurs 5 times.
The number 5 occurs 7 times.
The number 6 occurs 6 times.
The number 7 occurs 3 times.
The number 8 occurs 5 times.
The number 9 occurs 6 times.
Explanation:
int[] randomNum = new int[10];
Your randomNum integer array size is 10 but in for loop is you are trying fill the values up to 100 which causes the issues. For loop should run up to 10 values for filling your randomNum integer array.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.