Does anyone know how I can output the single corresponding value in a parallel array? Say this is a pair (a | 1, b | 2, c | 3, etc., etc.). If the user enters a then 1 would print.
Do a traditional indexed linear search, then use the index to get the second value.
Example:
for(int i = 0; i < array1.length; i++){
if (array1[i].equals(SEARCH_TERM_HERE)){
return array2[i]; // Or print, etc.
}
}
if you search 'a' retrieve the index of 'a' from array1 and print it
for (int index = 0; index < array1 .length; index ++) {
if (array1[i].equals("a")){
System.out.println(array2[index]);
break;
}
}
Related
I need to create an array, compare each pair of this array, and then find and print the largest element of each pair. I have created an array like below, but it's printing me only the two largest of the whole array!
public class Main {
public static void main(String[] args) {
int[] arr = {1, -5, 2, 6, 10, 7};
int a = arr[0];
int b = arr[1];
for (int i = 0; i<arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (a > b || b > a) {
a = arr[i];
b = arr[j];
}
}
}
System.out.println(a);
System.out.println(b);
}
}
In the example below, I have 3 pairs (6 elements) and I want to get maximum of each pair as an example:
Input: {1, -5, 2, 6, 10, 7}
Output: 1, 6, 10
I appreciate any help you can provide.
Your program does not print the two largest numbers. It prints the two last numbers of the array. If you add a 200 in the mid of the array, it will still print 10 and 7.
Also, the System.out.println()-lines are outside any loop, so they will run only once.
If you want to get the higher number out of the first and second, the third and fourth, fifth and sixth element and so on (due to the expected output, I assume this is what you want to get), then the for-loop will fail like this. On each run of the loop, it will check if a > b or b > a. If that's the case, a gets the value of arr[i] and b the value of arr[j]. On the last run, i will be the second last value and j the last value of the array, so you will always get the last two elements. Unless you compare two times the same value in the array, then a and b will get the same value and nothing will change anymore from there.
If you want to compare the pairs like I described, then maybe you should instead try something like this:
for(int i = 0; i < arr.length; i+=2)
{
if(!(i == arr.length-1)) // in case there is no i+1 index anymore
{
if(arr[i]>arr[i+1])
{
System.out.println(arr[i]);
}
else if(arr[i+1]>arr[i])
{
System.out.println(arr[i+1]);
}
}
}
An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.
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.
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.
Can anyone explain me what the following statement from the below code means..??
for (j = 0; j < arrayOfInts[i].length;
j++)
I'm learning Java language and having a very hard time figuring it out..
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Java doesn't really have multidimensional arrays, it has arrays that can contain other arrays. That code takes the ith item from the misleadingly named arrayOfInts. This item is itself an array of integers, so it's taking the length of this array. (That was stored in another array.) So, for example in this code:
int[][] array2d = new int[][] {
new int[] {1}, // stored at array2d[0]
new int[] {2, 3, 4} // stored at array2d[1]
}
the following are true:
array2d.length == 2 (The "multidimensional" array contains two other arrays.)
array2d[0].length == 1 (The first of which has one element: 1.)
array2d[1].length == 3 (The second has three elements: 2, 3, 4.)
There is no multidimensional array in Java. All there is is arrays of arrays.
arrayOfInts is such an array of arrays of ints. So arrayOfInts[i] is an array of ints, and
for (j = 0; j < arrayOfInts[i].length; j++)
iterates over every element of this array, i.e. it iterates over all the elements in the array of ints stored at the index i of the array of arrays of ints.
You could see it as a big box containing N smaller boxes, each smaller box containg a given number of integers. arrayOfInt is the big box. arrayOfInt[i] is the ith smaller box in the big box. And the loop iterates over every integer in this smaller box.
In Java two-dimensional arrays are implemented is a one-dimensional array of one-dimensional arrays.
for (j = 0; j < arrayOfInts[i].length; j++)
arrayOfInts[i].length means length of the ith row of an arrayOfInts.
int[][] a = new int[2][4];
This two-dimensional array will have two rows and four columns. This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and two one-dimensional arrays of 4 elements to represent the contents of the rows.
+-----+ +-----+-----+-----+-----+
|a[0] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+ In Java two-dimensional arrays are implemented is a
one-dimensional array of one-dimensional arrays -- like this.
+-----+
| | +-----+-----+-----+-----+
|a[1] | -> | [0] | [1] | [2] | [3] |
+-----+ +-----+-----+-----+-----+
j = 0; j < arrayOfInts[i].length
Cause you array is 2-dimensional, inner element of array will be array to.
So you getting the element(which is array) arrayOfInts[i] and calculates the length arrayOfInts[i].length, in other words:
int[] element = arrayOfInts[i];
int length = arrayOfInts[i].length;
Think of arrayOfInts[i][j] as a two-dimensional grid, like a spreadsheet. To help visualize, let's say that [j] represents the column index, and [i] represents the row index.
The explanation is then:
// iterate through every column j in the current row i:
for (j = 0; j < arrayOfInts[i].length; j++)
In your code , see the words int [][]arrayOfInts=...
It is a 2-dimensional array.2 dimensional arrays are nothing but arrays of arrays
It means simply there will be many normal 1-d arrays, and another array having references of each 1-d array.
So, the explanation of line, for(j=0;j<arrayOfInts[i].length;j++)is given below:
first, lets give focus to the wordsarrayOfInts[i].length
I already told you arrayOfInts is an array of arrays. So, arrayOfInts[i] points to the ith array.The word,arrayOfInts[i].length returns the length(i.e number of elements in an array) in the ith array of arrayOfInts.
The loop continues to happen until the j is less than then number of elements in the 1d array(less than (don't use equal to) because arrayOfInts[i][0] will be the first element).