How to limit printing occurrences in a array? - java

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");
}
}
}

Related

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 to display the numbers

I'm new to coding with Java and I'm having trouble writing this program.
User enters an integer from 0 to 9 and a pyramid is displayed. For ex:
User input: 5
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
This is all I have thus far (I'm truly stumped)
import static java.lang.System.*;
import java.util.Scanner'
import java.util.*;
public class pyramid
{
public pyramid()
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++)
{
for (int j = 0; j < num - 1; j++)
{
System.out.println(" ");
}
}
}
}
Any help is welcome and appreciated. Thanks!
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
pyramid();
}
public static void pyramid() {
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++) {
for (int j = 0; j < num - i; j++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.printf("%d ", j);
}
for (int j = 2; j <= i; ++j) {
System.out.printf("%d ", j);
}
System.out.println();
}
}
}
Start tabulating what you know, to find a pattern. Say you have height 3:
······_1
···_2 _1 _2
_3 _2 _1 _2 _3
Where · is a space for alignment purposes, _ a space reserved for the second digit.
Row 0 1 2
Spaces in front 6 3 0 (3 * (num - i - 1))
So you want to loop j to print that number of spaces, then make another loop (not inside j, but after it) to print the descending numbers to 1, then another loop to print ascending numbers back to i+1. Using System.out.printf with format %2d will print the _ space on single-digit numbers.

Can't trace an java.lang.ArrayIndexOutOfBoundsException:

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.

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]

stop a loop from asking user input

problem here is that we want the program to stop the loop/stop asking integers when '-1' is inputted by the user that it wont have to get the maximum length of our array
import java.util.Scanner;
public class DELETE DUPLICATES {
public static void main(String[] args) {
UserInput();
getCopies(maxInput);
removeDuplicates(maxInput);
}
static int[] maxInput= new int[20];
static int[] copies = new int[20];
static int[] duplicate = new int[20];
//get user's input/s
public static void UserInput() {
Scanner scan = new Scanner(System.in);
int integer = 0;
int i = 0;
System.out.println("Enter Numbers: ");
while(i < maxInput.length)
{
integer = scan.nextInt();
maxInput[i] = integer;
i++;
if (integer == -1)
break;
}
int j = 0;
for(int allInteger : maxInput) {
System.out.print(allInteger+ " ");
j++;
}
}
//to get value/number of copies of the duplicate number/s
public static void getCopies(int[] Array) {
for(int allCopies : Array) {
copies[allCopies]++;
}
for(int k = 0; k < copies.length; k++) {
if(copies[k] > 1) {
System.out.print("\nValue " + k + " : " + copies[k] + " copies are detected");
}
}
}
//remove duplicates
public static void removeDuplicates(int[] Array) {
for(int removeCopies : Array) {
duplicate[removeCopies]++;
}
for(int a = 0; a < duplicate.length; a++) {
if(duplicate[a] >= 1) {
System.out.print("\n"+a);
}
}
}
}
Example:
If we input :
1
2
3
3
4
5
-1
The result of our program is : 1 2 3 3 4 5 -1 0 0 0 0 0 0 0 0 0 0 0 0 0
We want the result to be like: 1 2 3 3 4 5
We need your help guyz . practicing our programming 1 subject hope we could get some help here
You can do a following change just to print the required values:
for(int allInteger : maxInput)
{
if(allInteger == -1)
break;
System.out.print(allInteger+ " ");
j++;
}
but, better change would be to rethink your design and use of data structures.
The maxInput array is of specified size that is 20, so it will have that no. of elements and prints the default value of int.
You can use List instead and check the size for max input and exit loop
If you don't need to use an array, then a Collection has lots of advantages. Let's use a List:
static int maxInputCount = 20;
static ArrayList<Integer> input= new ArrayList<>();
...
for (int i = 0; i < maxInputCount; i++)
{
integer = scan.nextInt();
if (integer == -1)
break;
input.add(integer);
}
for(int integer : input) {
System.out.print(integer+ " ");
}

Categories