User input java array - java

I need to create a program that will query the user for the size of a 2-dimentional array, and then fill the array with sequential integer data, starting with a user defined initial vale. I have some part of the program but I am stuck at the end.

What you want is this:
int value = scanner.nextInt();
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
array[i][j] = value + i * columns + j;
}
}
Try that out and it should work as expected.
Input:
2
2
5
Output:
[5, 6]
[7, 8]
Be sure to use Arrays.deepToString(array) to print out the array properly.
This will print out the row and column it is going to request for, then prompt you to fill it in.
Also:
array[rows][columns] = scanner.nextInt();
Will not work as you expect. That will fill in a single cell in the array, not to even mention it will throw an IndexOutOfBounds exception.

Related

Display the combinations and the number of combinations without the same value of the two array

I need to create a function that will accept two arrays of integers. Display the combinations and the number of combinations without the same value.
Example:
Array 1 = { 1, 2, 3 };
Array 2 = { 2, 3, 4 };
Output :
1,2
1,3
1,4
2,3
2,4
3,2
3,4
Combination count : 7
I've seen a lot of complicated codes here and can't find the exact goal that I am looking for so far, While waiting for someone to help I will just keep browsing and searching. Also I'm using Java 7.
Try this.
Note: This code is considering given example. There are no validation done. You can add it if needed.
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array2.length; j++) {
if(array[i] != array2[j]){
System.out.println("Combination "+array[i]+" "+array2[j]);
count = count +1;
}
}
}
System.out.println("Combination "+count);

Comparing elements in a circular array(java)

i am trying to formulate a for loop that will take an array, for instance of 5 elements, and will allow me to treat a[0] as if it is after a[4], and a[4] as if it was before a[0].
I cannot change the array, and it stores a thread in each element, so i would rather make it as simple as possible to not corrupt the contents of the thread(threads are synchornized and using reentrantlock - so the question is only about array).
I want to make this simple for loop:
for (int i = 0; i < ARRAYSIZE; i++)
to allow me to treat it as if it was a cyclic array. I thought of using the mudolo operation to achieve that, but that doesn't work either. here's what i tried:
for (int i = i+1 % n; i < ARRAYSIZE; i++)
but that doesn't work as well. What I am trying to do is basically check if array[i] is larger than array[i+1] or array[i-1].
would appreciate your assistance.
Use the modulo operator on the loop variable i by the size of the array:
public static void main(String [] args) {
int [] arr = {1, 5, 4, 3, 3, 4, 3, 1};
int ARRAYSIZE = arr.length;
for (int i = 0; i < ARRAYSIZE; i++) {
int index = i % ARRAYSIZE;
int indexUpper = (i + 1) % ARRAYSIZE;
//access array using index
if (arr[index] == arr[indexUpper]) {
System.out.format("Elements %d and %d are equals.\n", index, indexUpper);
}
}
}
Note how for the upper value you want to cycle through, you need to do (i + 1) % ARRAYSIZE to ensure you get the next element. To get the element two places over, add 2 instead, or whatever modifier you choose.
This test shows how elements 7 and 0 are equal because it is cyclical.
Output:
Elements 3 and 4 are equals.
Elements 7 and 0 are equals.

Adding data into a 2-D array by columns

I am currently trying to construct a data table in Java for my data. However, my data is arranged in columns (so for one column header, say "amount run", I have an array for all the values of "amount run"). In other words, I have an array of values for all the values of "amount run", and I need to arrange those into a column and not a row. So my question is "is there a way to intialize a 2-D array so that one can initialize it column by column (since the only way I know of initializing a 2-D array is via doing
Object[][] array = { {"word1","word2"},{"word3","word4"}}
However, this is by rows and not by columns. So, how do I instead initialize it so that "word3" and "word2" are in the same "array" (as "word1" and "word2" are presently in the same "array").
(It's best if the solution does not use loops, but if that is the only way, that is fine)
To get the entire array filled in any way but the one you've already defined, you must know the length your array will be. You have two options when doing so. You may either preset a determined array length and width,
Object[][] array = new Object[3][27];
or you may ask the application user for one.
System.out.print("Please enter an array length and column length: ");
int m = input.nextInt();
int x = input.nextInt();
Object[][] array = new Object[m][x];
After you know your array size
// If you are initializing by user input, then
System.out.println("Enter column one: ");
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = input.nextLine();
}
}
// Will not end until the column has finished by filled with the added user input.
// You will loop until your entire array.length is filled
// Same basic principle if you are not looking to use user input.
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = someObject; // someObject meaning some predetermined value(s)
}
}
Hope this helps!
Java dont have an especific constructor to do the task you are asking for, however you can resolve your problem with for loops.
for (int i = 0; i < columns; i++){
for(int j = 0; j < rows ; j++){
array[j][i] = “word” //initialize with some value
}
}
With this code you are able to initialize the array column by column.

Adding values from HashSet to 2D Matrix

I have a Map structure that contains an Integer as a key and a set of Objects as the values. However, I have overriden the toString method to get the Integer values of the values. So, example, the Map would look like
Key: 1 Values: [1, 2, 4]
I am having a bit trouble constructing a 2D Matrix out out this Map Structure. When I am looping through, I am checking to see if my iterator value is a key in the Map but I am having trouble checking to see if the second iterator is equal to the set value. This is the part of the code in question
for (int i = 1; i < this.adjacencyMatrix[0].length; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i < this.adjacencyMatrix.length; i++) {
System.out.print(i + " ");
for (int j = 1; j < this.adjacencyMatrix[i].length; j++) {
if (this.nodes.containsKey(i)) {
// Handle the set
this.adjacencyMatrix[i][j] = 1;
} else {
this.adjacencyMatrix[i][j] = 0;
}
System.out.print(this.adjacencyMatrix[i][j] + " ");
}
System.out.println();
}
My matrix right now will print 1's for the entire row of the map keys.
Example, if 4 is a key, the entire 10 rows will all be printing 1. However, say I have a mapping like 4-- [1, 2, 4] only 1, 2, 4 should have 1's in the given row, all the rest should be 0.
The if-condition (containsKey) is true (or false) for every step of the inner loop.
The inner loop should be replaced by two loops: First loop on the index j and initialize all values to 0. Then iterate on the elements in the nodes set, take each value and use it as index:
adjacencyMatrix[i][value] = 1

What do I need to do to my current code to make the program run a multiplication table (using a two dimensional array)?

I'm trying to make a Java program that uses the input value from a user to calculate and list the products of two numbers up to the entered number. Like if a user enters 2, the program should calculate the products between the two numbers (1 *1, 1*2, 2*1, 2*2) stores the products in a two-dimensional array, and list the products. I'm not sure that I totally understand arrays and so I feel as though my code is problem not right in many instances, can someone please tell me what I should do to my current code to make it work properly. Thanks in advance! :)
import java.util.Scanner;
public class ProductTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputString;
char letter = 'y';
// Prompt the user to enter an integer
while(letter != 'q') {
System.out.print("Enter a positive integer: ");
int integer = input.nextInt();
// Create an two-dimensional array to store products
int[][] m = new int[integer][3];
for (int j = 1; j <= m.length; j++) {
m[j][0] = input.nextInt();
m[j][1] = input.nextInt();
m[j][2] = input.nextInt();
}
// Display the number title
System.out.print(" ");
for (int j = 1; j <= m.length; j++)
System.out.print(" " + j);
System.out.println("\n--- ");
// Display table body
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Prompt the user to either continue or quit
System.out.print("Enter q to quit or any other key to continue: ");
String character = input.nextLine();
inputString = input.nextLine();
letter = inputString.charAt(0);
}
}
}
You can achieve your multiplication table by iterating over 2 counter variables as you already did in your output
// Display table body
// loops running out of bounds (until m.length + 1 instead of m.length-1)
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) { // missed to increment j here
System.out.printf("%4d", i * j);
}
System.out.println();
}
Arrays should be based on 0, that means an array with 3 fields has the indexes 0, 1, 2. So the last index is length-1. Your condition <=m.length+1 runs out of bounds. index<length will work since 2 is less than 3, but not 3 less than 3.
You have also a typo: In the inner loop you are doing an increment of i instead of j, so the loop will run infinite.
Try to create an outer and inner loop as you did, but with start index 0 and end condition index<inputValue. Calculate multiTable[index1][index2] = (1+index1)*(1+index2).
Then do a similar loop and print the array fields. You don't need to use an array, you could output directly as you did. But you wanted to practice handling arrays.
Since you want to learn and understand, I don't like just to write the code. imagine an array with 3 fields having the indexes 0, 1, 2:
index 0 | 1 | 2
value 1 | 2 | 3
Now you would check the length at first, that's 3. You start with 0 and count while the counter does not reach the length since the zero based index is 1 below our natural order (0,1,2 vs. 1,2,3). That is the case as long the index is below the length, meaning index<length.
Try this logic (pseudo code). To simplify the problem we include the 0 in our product table. So we get 0*0, 0*1, 0*2... Doing so, we do not have to ignore index 0 or to calculate between index 0 should represent value 1.
maxNumber = userInput()
outer loop idx1 from 0 to maxNumber
inner loop idx2 from 0 to maxNumber
array[idx1][idx2] = (idx1) * (idx2)
end loop
end loop
Do the same to dump your generated array to screen.
First get it running. Afterwards you could try to alter the logic, so that it shows you only numbers from 1 to max.

Categories