Can't trace an java.lang.ArrayIndexOutOfBoundsException: - java

I'm trying to solve following simple programming exercise: "Write a program that reads the integers between 1 and 10 and counts the occurrences of each. Assume the input ends with 0". I've come up with following solution. I'm not familiar with debugger and trying trace ArrayIndexOutOfBoundsException last 3 hours. Maybe someone is able to see the where ArrayIndexOutOfBoundsException occurs?
import java.util.Scanner;
public class Exercise07_03 {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter up to 10 integers between 1 and 10" +
"inclusive (input ends with zero): ");
int i = 0;
do {
numbers[i] = input.nextInt();
i++;
} while (numbers[i] != 0 && i != 9);
displayCounts(countNumbers(numbers));
}
/** Count the occurrences of each number */
public static int[] countNumbers(int[] numbers) {
int[] counts = new int[10];
for (int i = 0; i < counts.length; i++)
counts[numbers[i] - 1]++;
return counts;
}
/** Display counts */
public static void displayCounts(int[] counts) {
for (int i = 1; i < counts.length + 1; i++)
if (counts[i - 1] != 0)
System.out.println(i + " occurs " + counts[i - 1] + " time");
}
}

The problem is here:
public static int[] countNumbers(int[] numbers) {
int[] counts = new int[10];
for (int i = 0; i < counts.length; i++)
counts[numbers[i] - 1]++;
return counts;
}
The solution is in:
counts[(number - 1 > 0) ? number - 1 : 0]++;
This checks if (number-1) is greater than zero. If not it uses 0. If true it uses number -1.

counts[numbers[i] - 1]++;
results -1 if input contains 0.

Related

Why does my code output an extra "0" after finding the most frequent integer in an array?

An example of integers entered would be: 5 9 2 2 1 4 5 5 -1 and my code's output is "5 0". In this example array, I only need it to display "5 ". Try it yourself with any combination of integer input, ending your input with a -1 and you'll get the most frequent integer with a zero. Any ideas why my code does this?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] b = new int[21];
for (int i = 0; i < b.length; ++i) { //integer input from user
b[i] = scnr.nextInt();
if (b[i] == -1) { //array input stops when input is -1
break;
}
}
int maxcount = 0;
int element_having_max_freq;
for (int i = 0; i < b.length; ++i) {
int count = 0;
for (int j = 0; j < b.length; ++j) {
if (b[i] == b[j]) {
count = count + 1;
}
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = b[i];
System.out.println(element_having_max_freq+ " ");
}
}
}
}
Your array is of size 21 and initialized as all zeros. All numbers you don't overwrite with the user input will remain zeros, which means that in the case of your test input 5 9 2 2 1 4 5 5 -1, you get another 12 zeros.
Try placing a breakpoint after the part of the code that parses the user input and have a look at b.

Printing spaces to align numbers according to my pyramid pattern

It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.

How do I get the right output for this array?

I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]

How to limit printing occurrences in a array?

So close to having this program working but I'm stuck.
What I want it to do is simply print out the numbers that have actual occurrences,
so if the user inputs : 1, 2, 3, 2, 6
It needs to display
1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times
What I'm actually getting with the same input is something like:
1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times
5 - 0 times
6 - 1 times
I need to remove the case where there are no occurrences.
import java.util.Arrays;
import java.util.Scanner;
public class CountOccurrences
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
//Create Array for numbers
int numbers[] = new int[100];
//Prompt user input
System.out.println("Enter integers between 1 and 100: ");
//For loop to continue input
for (int i = 0; i < numbers.length; i++) {
int next = input.nextInt();
//Breaks loop if 0 is inputted
if (next==0)
{
break;
}
numbers[i] = next;
}
//Calls on countInts method
int[] count = countInts(numbers);
//Calls on display counts
displayIntCount(count);
}
//Counts each instance of a integer
public static int[] countInts(int[] ints)
{
int[] counts = new int[100];
for(int i = 1; i <=counts.length; i++)
for(int j=0;j<ints.length;j++)
if(ints[j] == i)
counts[i-1]++;
return counts;
}
//Displays counts of each integer
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++)
System.out.println((i+1) +" - " +counts[i] +" Times");
}
}
Just use a simple if statement to check if counts[i] is not 0, like this:
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((i+1) +" - " +counts[i] + " Times");
}
}
}

stuck in contraints in a easy exercise

I am trying to solve this exercise, It seems easy this, but I can not understand the contraints -rules, It says:
the number may be represented on one or two hands;
if the number is represented on two hands, the larger number is given first
The rule number 2 I can not understand for example if it says 3, I have 3, 2+1, 1+2 (this not because its repeated), if it says 6 we have 6, 5+1, 4+2, 3+3, 2+4 + 1+5 but the correct output is 3, can someone guide me in this problem?? for 7 is 2, and 8 is 2, 9 is 1, and 10 is 1.
this is my code:
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= tot; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
Its simple - if you are going to give the number using both the hands (2 hands) then you will first need to give the larger number which comprises the overall number -
eg for 7 (4+3 OR 5+2) when represented using 2 hands - give 4 first !
other option for 7 (3+4, 2+5) are invalid since it will make us to list the smaller number first which violates the rule #2
The number of the second hand must always be less than or equal to the number of the first hand. I believe the code below will work.
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= i; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}

Categories