Storing a value to the second dimension - java

I am working on a project in java and I was wondering how I can store a value to the second array container
I have
int[][] figure = new int[4][6];
I have the following for loop
public void ask(){
for(int i =0;i<Division;i++){
System.out.println("Enter sale for division " + i );
for(int j =0; j<4;j++){
System.out.println("For quarter " + j);
int input = keyboard.nextInt();
}
}
}
How can I set input equal to the second array container [][]<--

A 2D array is an array of arrays, therefore you can:
Add values to 2D arrays with double for-loops.
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = yourValue;
}
}
Or do array[index][index] = yourValue.
Example:
Say I want to add a value to the first index of the first array in a 2D array of type int.
I would do:
array[0][0] = 56.
Then, to access a value from the array, I would do:
int value = array[0][0]

Related

i want to create a bar chart of array with given user inputs

You are given a number n, representing the size of array a.
You are given n numbers, representing elements of array a.
You are required to print a bar chart representing value of arr a.
A bar chart of asterisks representing value of array a
SAMPLE INPUT:-
5
3
1
0
7
5
SAMPLE OUTPUT:-
I tried getting this input from this approach can anyone help me? What should I do to get the same?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
int x = arr[i];
for (int j = 0; j < x; j++) {
System.out.print("*" + "\n");
}
System.out.println();
}
}
}
A 2D array of chars may be used to represent the graph field to "draw" vertical bars char[][] map.
The dimensions of this array are:
height: the maximal number in the input arr
width: the number of columns (arr.length) plus an empty column between each asterisk bar, that makes: 2 * arr.length - 1
it may be better to have a parameter space between the bars and calculate the width of map accordingly: (space + 1) * arr.length - space
Populate each row of the map with default whitespaces (maybe using Arrays.fill).
Nested loops: Fill asterisks in the relevant columns from bottom to top, calculate indexes of the columns with regard to space parameter.
Loop: Print each row of map converting the char[] into String.
Coding is left for exercise.
//finding largest element in an array
int l = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] > l)
l = arr[i];
}
//traversing using largest element as no. of rows
for(int i = l; i > 0; i--) {
for(int j = 0; j < n; j++) {
if(i <= arr[j])
System.out.print("* ");
else
System.out.print(" ");
}
System.out.println();
}

Adding Items to an array in Java

I wanted to create an array that has a length specified by the user, and also wanted to have it filled by a loop command, and then it should be copied to another array by another loop command, so I wrote a code but it generates an error when trying to run it
Scanner input = new Scanner(System.in);
System.out.print("Hello, Please enter the amount of numbers: ");
int n = input.nextInt();
int array1[] = new int[n];
int array2[] = new int[n];
System.out.print("Please enter your numbers: ");
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [index] = array1 [i];
}
for (int i = 0; i < n; i++) {
array2[i] = array2[i];
}
System.out.println("Array 1 is: " +Arrays.toString(array1));
System.out.println("Array 2 is: " +Arrays.toString(array2));
so the code runs with a single issue that all the elements are set to zero if I entered the elements of the array less than the size of the array "n".
but if for example, I entered the size is 5, and tried to fill the array, the program crash if I tried to add any number larger than 5 in the array.
I know that the problem sounds silly, but I'll be grateful if you guys helped me out with it.
You have two problems in your code.
Substitute your for(s) with the following code:
for (int i = 0; i < n; i++) {
int element = input.nextInt(); //elemet inserted by the user
array1[i] = element;
}
for (int i = 0; i < n; i++) {
array2[i] = array1[i];
}
for add item in array
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [i] = index ;
}

I need help in this (Sums In Loops)

Hello Guys i just need help this is the problem I want to solve:
Input data will contain the total count of pairs to process in the
first line.
The following lines will contain pairs themselves - one pair at each
line.
Answer should contain the results separated by spaces.
Example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
i write the code and here it is
public class SumsInLoopAdvanced {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
int a =0;
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
a = arr[j]+arr[i];
}
System.out.print("Answer: \n" + a);
}
}
}
it just 245+15 the wrong answer so could you help me ??
your code is broken here:
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
because you are overwriting the previously filled array: arr[i]
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
If i got it right you need to print a sum of two arrays entries for each index.
First of all you are using the same array and you are overwriting everything that you did in a first loop by the second loop.
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
//writing into the same array starting with 0 index
arr[j] = reader.nextInt();
}
And if I got this exercise right you don't need a nested loop, you need to to find a sum of two array elements from different arrays with the same index.
something like this:
for (int i = 0; i < num; i++) {
a = arr1[i] + arr2[i];
System.out.print(a + " ");
}
You're overwriting the values in arr on your second loop.
If you want to collect two sets of values, you'll need two arrays. (Well, not need, but that would be the reasonable way.) Also note that you don't need or want the nested loop at the end; just add the ith entry from the first array to the ith entry of the second.
Side note: Instead of a hardcoded upper bound on the array (250), use num so you know it's always big enough (e.g., if I tell you I'm going to enter 300 numbers, your code will blow up). int[] arr = new int[num];
But, now that the problem you're trying to solve is quoted in the question, note that your code doesn't want to read in a bunch of values, then read in a second bunch of values, and then add those together. The assignments says you'll enter things like "100 8" and then "15 245" and be meant to add those to get 108 and 260.
So you'll need to read the first number, then the second, add those and store them in your (one) array; then read the next third number, and the fourth, add those together and store them; and then output the results.

Displaying reverse numbers array

So I have to write a program that accepts 10 numbers (ints) from the keyboard. Each number is to be stored in a different element of an array.
Then my program must then display the contents of the array in reverse order.
int [] array = new int [10];
for(int i = array.length - 1;i >= 0; i--)
{
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
JOptionPane.showMessageDialog(null, array[i]);
}
I tried to put the JOPtionPane.showMessageDialog outside of the loop but then the program can't find the integer "i". I don't know what to do here :/ Please help :P
You need to enter your data first, then display it thereafter in the order you desire...
int [] array = new int[10];
for (int i = 0; i < array.length - 1; i++) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i + 1)));
array[i] = number;
}
for (int i = array.length - 1; i >= 0; i--) {
JOptionPane.showMessageDialog(null, array[i]);
}
I'd also be tempted to simply construct a StringBuilder for your final results and then just show the message dialog once only, rather than for every element of the array, but that's up to yourself :)
i belongs to the loop scope, that's why you can't use it outside of the loop.
To print the reversed array use another loop
// insert the data to the array
int [] array = new int [10];
for(int i = array.length - 1 ; i >= 0 ; i--) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
// print the array
for (int i = 0 ; i < array.length ; ++i) {
JOptionPane.showMessageDialog(null, array[i]);
}
That's because you've declared in in for loop, so it has loop scope. Declare it before loop to reuse it after loop finishes
int i;
for(i = array.length - 1;i >= 0; i--)
After that, you can make another loop:
for(i = 0; i < array.length; i++)
to print it in reverse order.
You need two for loops. The first iterates from 0 to 9 and asks for the number and puts it in the array. The second iterates from 9 to 0 and prints the numbers in the array

JAVA displaying an array as matrix and random numbers are equal to the minimum

I have to write a JAVA program where a user set the number of columns and rows of a 2d array. Then he should choose a minimum and a maximum. After that, the array is filled randomly.
I writed this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class array2d
{
public static void main (String[] args) throws java.lang.Exception
{
int rows, col, min, max;
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter number of rows and columns:");
rows = scan1.nextInt();
col = scan1.nextInt();
int[][] a = new int[rows][col];
System.out.println("Enter min and max:");
min = scan1.nextInt();
max = scan1.nextInt();
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
a[i][j] = min - (int)Math.random()*(max-min+1);
}
}
//Display on the screen
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
System.out.print(a[i][j]+ " ");
}
}
...
}
}
Then we should run a program to see if the first number of each row is a divisor of all the row:
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
if(a[i][0]%a[i][j]==0)
{
System.out.println(a[i][j]);
}
else
System.out.println("None");
}
}
That's working properly, but the generated array on my computer is displayed like that (CMD output):
And as you see in the picture, all randomly filled random are equal to the minimum specified.
So how can I display this array as like matrix and why the random numbers are showing like this.
Math#random return a number between 0.0-1.0, but less then 1.0. This does in fact make your calculation look like the following min-0, since you are parsing it as int. Due to this you are allways saying 0*(max-min+1).
In order to achive what you want you need to add braces and add to min.
For your representation problem, add a System.out.println after you finished the inner loop.
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++) {
a[i][j] = min + (int)(Math.random()*(max-min+1)); // You need brackets and add it to min
}
}
//Display on the screen
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++){
System.out.print(a[i][j]+ " ");
}
System.out.println(); // You need a linebreak
}
All slots of your array get filled wit the 10 value in your example, min in general :
a[i][j] = min - (int)Math.random()*(max-min+1);
yields
a[i][j] = 10 - (int)Math.random()*(10);
Math.random() returns a double greater than or equal to 0.0 and less than 1.0 , so rounded to an int, it is 0 .
so
a[i][j] = 10 - (0*(10)); // this yields 10, the value of "min"
Where you have:
a[i][j] = min - (int)Math.random()*(max-min+1);
You actually mean:
a[i][j] = min + (int) (Math.random()*(max-min+1));
The first one casts Math.random() to an int (giving zero), then multiplies it by (max-min+1) (giving zero), then subtracts it from min (giving min).
The second one multiples Math.random() by an int (giving a random double in the range [0,max-min+1) ), then casts it to an int (giving a random int in the range [0,max-min] ), and then adds min (giving a random int in the range [min,max] ).

Categories

Resources