Creating an array that counts up to a given number - java

I need help creating an array that counts up to a given number. The output should look something like this:
Enter a positive integer: 8
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
Here is what I have so far:
Scanner input = new Scanner(System.in);
int[] myList = new int[1];
System.out.print("Enter a positive integer: ");
promptUser(myList);
int[] testArray = { 1, 1, 2, 3, 5, 8, 13 };
System.out.print("Test array: ");
printArray(testArray);
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
}
public static void promptUser(int[] a){
Scanner input = new Scanner(System.in);
for(int i=0; i<a.length; i++){
a[i] = input.nextInt();
}
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++)
System.out.print(array[i]);
}
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
}
Everything seems to work alright except for the last method called countingUp.
Thank you so much!

public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
change this to
public static int[] countUp(int n){
int [] temp=new int[n];
for(int i=0; i<n; i++){
temp[i]=i+1;
}
return temp;
}
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
In this line change to
int[] countingUp = countUp(n);
for(int i=0;i<countingUp.length;i++){
system.out.println(countingUp[i]+" ");
}

We can start by extracting the common logic of counting by providing an initial message, the number of times to run, an initial value and an increment. Something like,
private static void count(String msg, int times, int init, int inc) {
System.out.print(msg);
for (int i = 0; i < times; i++) {
System.out.print(' ');
System.out.print(init);
init += inc;
}
System.out.println();
}
We can then implement the entirety of the requirements with something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
System.out.flush();
do {
int num = scanner.nextInt();
count("Counting up:", num, 1, 1);
count("Counting down:", num, num, -1);
count(String.format("The first %d multiples of 5:", num), num, 5, 5);
count(String.format("The first %d multiples of 10:", num), num, 10, 10);
System.out.print("Enter a positive integer: ");
System.out.flush();
} while (scanner.hasNextInt());
}
This will produce the requested output given an input of 8, and will then prompt for more input.

First of all, If you are trying to change the Array Size Dynamically then It is NOT POSSIBLE in java Take a look # this accepted answer. I recommend you to use ARRAYLIST instead.
Although I have found below mistakes in your code. In your code I do not understand two things.
First One:
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
What is the value of n? I think it is not being initialized.
Second One:
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
What will return this function? You have not returned anything from it.

Apparently you don't need an array just follow below steps.
First create a class which handle all your calculating and counting
class SupportCounting {
public void countUp(int num) {
System.out.print("Counting up : ");
for (int i = 1; i <= num; i++) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void countDown(int num) {
System.out.print("Counting Down : ");
for (int i = num; i > 0; i--) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void printMultiple(int num, int scalefactor) {
System.out.print("First " + num + " multiples of " + scalefactor + " : ");
for (int i = 1; i <= num; i++) {
System.out.print(i * scalefactor);
System.out.print(" ");
}
System.out.println("");
}}
Then make use of that class in you main method
public class Counting {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = reader.nextInt();
SupportCounting sc = new SupportCounting();
sc.countUp(n);
sc.countDown(n);
sc.printMultiple(n, 5);
sc.printMultiple(n, 10);
}}
Hope that helps

Related

How can I know what number is repeated?

I'm trying to know what number is repeated in Java.
I'm using 1.8JDK and never enter in IF.
I don't know how can I do for program works, I'm hardstucked.
Can you check my code?
package exercici10;
import java.util.Scanner;
public class isRepeatedOrNot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
int[] myArray2 = new int[10];
for (int i = 0; i < 10; i++) {
myArray2[i] = myArray[i];
}
System.out.print("Enter 10 numbers: ");
// Get myArray.
for (int i = 0; i < 10; i++) {
myArray[i] = sc.nextInt();
}
// Print myArray.
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray2.length; j++) {
if (myArray[i] == myArray2[j]) {
System.out.println("Is repeated.");
return;
}
}
}
System.out.println("No numbers repeated.");
sc.close();
}
}
Thank you.
Regards,
Alex.
You do not need to have two arrays, it is enough to use one array and a function that will check if there is a repetition of a number:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
System.out.print("Enter 10 numbers: ");
// Get myArray.
for (int i = 0; i < 10; i++) {
myArray[i] = sc.nextInt();
}
System.out.println(isNumberRepeated(myArray));
sc.close();
}
public static boolean isNumberRepeated(int[] array)
{
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i]==array[j]) {
return true;
}
}
}
return false;
}
}
Input :
Enter 10 numbers: 1
2
3
4
5
6
7
8
9
10
false
Input 2 :
Enter 10 numbers: 1
2
3
4
5
54
6
7
54
9
true
You could use HashSet which doesn't allow duplicate values.
public static void main(String[] args) {
Integer[] myArray = {1, 2, 3, 1, 3, 4, 5, 7, 6, 3, 2};
HashSet<Integer> uniqueNumbers = new HashSet<>();
HashSet<Integer> repeatedNumbers = new HashSet<>();
for (Integer integer : myArray) {
if (uniqueNumbers.contains(integer)) {
repeatedNumbers.add(integer);
} else {
uniqueNumbers.add(integer);
}
}
System.out.println(repeatedNumbers);
}
Also if you need to modify your code to show number of times every number repeated, you could use hashmap.

How to output multiple values being stored into an array using a for loop on the same line?

I created my arrays and when I am entering the values for the arrays, they are being shown on separate lines for example...
Enter the values for the first array: 75
48
23
I would like the numbers to be shown on the same line and not sure how to do it. Thank you for your help.
public class CompareArrays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int arraySize;
System.out.print("Enter the array size: ");
arraySize = input.nextInt();
int[] array1 = new int[arraySize];
int[] array2 = new int[arraySize];
System.out.print("Enter the values for the first array: ");
for(int i = 0; i < arraySize; i++) {
array1[i] = input.nextInt();
}
System.out.print("Enter the values for the second array: ");
for(int i = 0; i < arraySize; i++) {
array2[i] = input.nextInt();
}
if(Compare(array1, array2)) {
System.out.println("Judgement: \t The arrays are identical");
}else {
System.out.println("Judgement: \t The arrays are not identical");
}
input.close();
}
public static boolean Compare(int[] array1, int[] array2)
{
for (int i = 0; i < array1.length; i++) {
if(array1[i] != array2[i]) {
return false;
}
}
return true;
}
}
When in the console inputting those values you are hitting enter which is why it looks like it is on different lines. If you want to input the values on 1 line you could possibly input them as a string and split it.
If you're looking to just print the array on one line you can do that with a basic for loop and using System.out.print().
int[] a = {1, 2, 3, 4};
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}

Random Shuffling an array of integers in Java [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.
A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}

How can I fix my code? 2D Array

I want to create a 2D array using the user's input and the creating random numbers in the second line.
E.g:
Output should be:
If the user enters "7" then:
1 2 3 4 5 6 7 (User's input)
0 2 4 8 9 8 5 (Random numbers)
but instead I only get one random number.
My code is working but I can't see to create the array correctly.
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for(int i=0; i<A.length; i++){
for (int j = 0; j<n; j++) {
A[i][j] = (int) (Math.random()*10);
}
}
System.out.println(A[1][n-1]);
System.out.print("Distance between exit i and exit j is: " + distance());
}
public static int distance(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter exit i: ");
int i = input.nextInt();
System.out.print("Please enter exit j: ");
int j = input.nextInt();
return i + j;
}
}
How can I fix it?
Would this help?
int n = input.nextInt();
Random rand = new Random();
int [][] A = new int[2][n];
for (int i = 0; i<n; i++) {
A[0][i] = i+1;
A[1][i] = rand.nextInt(10);
}
Am not too certain about what you mean by:
1 2 3 4 5 6 7 (User's input)
0 2 4 8 9 8 5 (Random numbers)
Do you want users to manually enter "1 2 3 4 5 6 7"?
Eitherway, here's something to help with the printing aspect:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for(int i=0; i<A.length; i++){
for (int j = 0; j<n; j++) {
A[i][j] = (int) (Math.random()*10);
}
}
for(int[] b: A)
{
for(int k: b)
{
System.out.print(k + " ");
}
System.out.println();
}
System.out.print("Distance between exit i and exit j is: " + distance());
}

bubble sort with recursive method and at the end comper two different arrays

I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so a kind of bubble sort for the first and second array togheter. I wrote this below, but I don t know how to compare with one method the two different arrays.
public static void main(String[] args) {
public static int[] macello(int[]A){
for(int i=0; i<A.length-1; i++){
for(int j=0; j<A.length-1-i;j++){
if(A[j]>A[j+1]){
int temp = A[j+1];
A[j+1]= A[j];
A[j] = temp;
}
}
}
return A;
}
public static void printArray2(int[]A){
for(int i = 0; i<A.length; i++){
System.out.print(A[i]+",");
}
}
Scanner scan = new Scanner(System.in);
System.out.println("Insert the capacity's array1: ");
int n = scan.nextInt();
int[]numbers1 = {n};
for(int i=0; i<n; i++){
System.out.println("Insert the value of each numbers: ");
int j =0;
numbers1[j] = scan.nextInt();
j++;
}
System.out.println("Insert the capacity's array2: ");
int m = scan.nextInt();
int[]numbers2 = {m};
for(int i=0; i<m; i++){
System.out.println("Insert the value of each numbers: ");
int j=0;
numbers2[j] = scan.nextInt();
j++;
}
macello(Arrays.equals(numbers1,numbers2));
printArray2(Arrays.equals(numbers1,numbers2));
}
}
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr).
Your code shows you understand how to acquire an array from the user, so we don't need to handle that.
Now what you're describing is bubbleSorting these two arrays. To do this, you need one -big- array that holds them both.
int combinedLength = array1.length + array2.length;
int[] combined = new int[combinedLength];
for(int i = 0; i < array1.length; i++) {
combined[i] = array1[i];
}
for(int i = 0; i < array2.length; i++) {
combined[array1.length + i] = array2[i];
}
// now you can bubbleSort
bubbleSort(combined);
arrayPrint(combined);
Ideally you wrap that logic in a merge method - this particular method leverages the Arrays and System classes to do some of the lifting for you. Obviously you could use the "naive" logic above if you want.
int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
If you also make a method that acquires an array, like this:
public int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
Then your code becomes very, very clean:
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
arrayPrint(c);
I made a driver to test each of these ideas out to make sure they all work. I am a bit concerned, though, because you mention recursion. As you can see in this driver, there is no recursion here. Also be aware that I take a number of shortcuts that are probably not allowed (such as System.arraycopy, Arrays.copyOf, and Arrays.toString). I just wanted to validate the various pieces of functionality. The message uses 1 indexing because that's what most people think in. If you enter 5 elements, they'll be 1-5. You and I know Java stores them 0 indexed, 0-4. It's just a matter of taste and UX.
import java.util.*;
public class BubbleSort {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
printArray(c);
}
public static int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
public static int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
public static void bubbleSort(int[] a) {
boolean swapped = true;
int j = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < a.length - j; i++) {
if(a[i] > a[i+1]) {
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
swapped = true;
}
}
}
}
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
}
And here's what I get when I run it
C:\files\j>java BubbleSort
Length?
5
Enter element 1:
1
Enter element 2:
5
Enter element 3:
3
Enter element 4:
9
Enter element 5:
7
Length?
5
Enter element 1:
2
Enter element 2:
6
Enter element 3:
4
Enter element 4:
0
Enter element 5:
8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Categories