How can I fix my code? 2D Array - java

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

Related

I have to take integers in an array and output them in random order

This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[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]);
}
}
}

Creating an array that counts up to a given number

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

How to create a empty set of array and fill it with user input and print it out?

Here is my code to fill an empty array :
package duplicate.terminator;
import java.util.Arrays;
import java.util.Scanner;
public class DuplicateTerminator {
public static void main(String args []){
Scanner number = new Scanner(System.in);
int a, num;
int[] integerset = null;
System.out.println("Enter Number: ");
num = number.nextInt();
Arrays.fill(integerset, num);
}
}
That is my code because I want to have this output.
I need to stack input numbers in array and print it out like this.
Sample Input/Output:
Enter number: 5
5
Enter number: 9
5 9
Enter number: 2
5 9 2
Enter number: 9
9 has already been entered
5 9 2
Enter number: 1
5 9 2 1
I would suggest using LinkedHashSet
because
you don't know the number of elements in your data container initially
you don't want duplicates and you don't want to go serially to check if there is a duplicate
you want to preserve order
Here is an example:
Set<Integer> numbers = new LinkedHashSet<>();
while(/*some logic to exit on special input*/) {
if(!numbers.add(userInputNum){
// number was already present
}
}
If you don't want to use LinkedHashSet or fill method in array this is an alternate way to do it.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int i, j;
int[] list = new int[10];
for (i = 0; i <= 9; i++)
{
System.out.println("Enter a number :");
list[i] = scan.nextInt();
for (j = 0; j < i; j++)
{
if (list[j] == list[i])
{
System.out.println(list[j] + " has already been entered");
i--;
}
}
for(j = 0; j <= i; j++)
{
System.out.print(list[j] + " ");
}
System.out.println();
}
}

Printing a 2d array in Java like a table [duplicate]

This question already has answers here:
How to print Two-Dimensional Array like table
(16 answers)
Closed 9 years ago.
I'd like to print an inputed 2-dimensional array like a table
i.e if for some reason they put in all 1s...
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Just like so above but in the console on Java eclipse, no fancy buttons and GUI's but in the console, here is what I have....
import java.util.Scanner;
public class Client {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i=0; i < table.length; i++) {
for (int j=0; j < table.length; j++) {
System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println(table);
}
}
And this is what I get when I input everything and the console terminates:
Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1
[[I#3fa1732d
Consider using java.util.Arrays.
There is a method in there called deepToString. This will work great here.
System.out.println(Arrays.deepToString(table));
Relevant here: Simplest way to print an array in Java
You need to print out the array separately from entering the number. So you can do something like this:
public class PrintArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
// System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
}
//System.out.println();
}
// System.out.println(table);
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
You'll have loop back through those arrays to print out the contents. an array's toString() just prints the reference value.
System.out.print(table) calls a method in array class that prints out the identifier of the vairable. you need to either create a for loop that will print out each element like System.out.print(table[i][j]) or use the Arrays class and say Arrays.toString(table);
Try copying this simple for loop to printing a 4x4 table:
Scanner input = new Scanner();
int numArray [] [] = new int [4] [4];
for ( int c = 0; c < 4; c++ ) {
for (int d = 0; d < 4; d++) {
System.out.print("Enter number : ");
nunArray [c][d] = input.nextInt();
}
}
for (int a = 1; a<5;a++) {
for (int b = 1; b <5;b++) {
System.out.print(numArray [a][b]+" ");
}
System.out.println();
}

Categories