Compare name of String and name of Array int[] [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have one matrix which has two rows and one column. Each row has specific name such as row0 and row1. I added some numbers in each row and column of this matrix. For example I have String index which can get one of the name of rows (row0 or row1). How can I check if index == "row0" then print row0[1] and if index == "row1" then print row1[1]??
int[][] s = new int[2][3];
s[0][0] = 5;
s[0][1] = 10;
s[0][2] = 15;
s[0][1] = 25;
s[1][1] = 30;
s[2][1] = 45;
int[] row0 = new int[]{s[0][0], s[0][1], s[0][2]};
int[] row1 = new int[]{s[0][1], s[1][1], s[2][1]};
String index = "row0";
// if index= row0
System.out.println(row0[1]);
// if index=row1
System.out.println(row1[1]);

In your example there is probably something wrong:
int[][] s = new int[2][3]; // two rows, three cols
s[0][0] = 5;
s[0][1] = 10;
s[0][2] = 15;
s[0][1] = 25;
s[1][1] = 30;
s[2][1] = 45; // <---- 2 is out of bounds
int[] row0 = new int[]{s[0][0], s[0][1], s[0][2]};
int[] row1 = new int[]{s[0][1], s[1][1], s[2][1]};
Anyway, you could use a Map for your matrix and then address the rows with a String:
// ...code for s here..
Map<String, Integer[]> matrix = new HashMap<String, Integer[]>();
matrix.put("row0", new Integer[] {s[0][0], s[0][1], s[0][2]});
matrix.put("row1", new Integer[] {s[0][1], s[1][1], s[2][1]});
String index = "row0";
// if index= row0
System.out.println(matrix.get(index)[1]); // row0[1]
// if index=row1
index = "row1";
System.out.println(matrix.get(index)[1]); // row0[1]

You can not check the equality of String objects with the == operator.
You have to use .equals() instead. This question has been asked many times in StackOverflow and this answer, explains it concisely.
What you want to do, is something like this:
final String ARRAY_NAME1 = "row0";
final String ARRAY_NAME2 = "row1";
String index = "row0";
if(index.equals(ARRAY_NAME1))
System.out.print(row0[1]);
else if((index.equals(ARRAY_NAME2))
System.out.print(row1[1]);
We got that out of the way.
Now, you say that you don't want to hardcode this and I absolutely understand.
So, if I were in your position, I would create a new class for this. It's really simple and easy to do, even for a total beginner.
//class can be named anything. (As long as it is meaningful)
public class IntegerArrayIdentity{
/*This class will have two variables.
A name, for comparison operations and
the integer array that it will represent.*/
public String name;
public int[] array;
/*Simple constructor. Takes the name and array as its parameters.
You can change it to only take a name as a parameter, in case
that you want to initialise the array later. Add new methods as you like*/
public IntegerArrayIdentity(String name, int[] array){
this.name = name;
this.array = array;
}
}
Then in your code, you can do:
int[] row0 = {8, 3, 5, 143, 27, 0};
IntegerArrayIdentity row0id = new IntegerArrayIdentity("row0", row0);
if(index.equals(row0id.name))
System.out.println(row0id.array[1]);
output -> '3'
All the above is just an example. You can implement it however you like.
Hope it helped.

Related

How do I debug arrays? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I have this assignment that I am having trouble on. I'm supposed to fix syntax error in the code to produce the desired number. I fixed the amount of arrays from 4 to 3 and added "[]" to the end of array in the for loop. I don't know what else there is to fix. Can anyone help?
//
// Fix the compiler errors. The program should display the value 6.
//
package debug5;
public class debug5 {
public static void rain(String[] args) {}
int val = 0; // initialize val to 0.
int array[] = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
// add up the values in the array.
for (int zx = 0;zx < array.length;zx++)
}
val += array;
{
system.out.println(val);
}
}
My version :
//
// Fix the compiler errors. The program should display the value 6.
//
package debug5;
public class debug5 {
public static void rain(String[] args) {}
int val = 0; // initialize val to 0.
int array[] = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
// add up the values in the array.
for (int zx = 0;zx < array.length;zx++)
}
val += array[];
{
system.out.println(val);
}
}
In addition to Rafael's answer, be careful with braces and where you'd like to system out.
public static void rain(String[] args) {
int val = 0; // initialize val to 0.
int[] array = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
//add up the values in the array.
for(int zx = 0;zx < array.length ;zx++){
val += array[zx];
}
System.out.println(val);
}
Above code will increment val with each value inside the array and sum inside val variable. Print is done afterwards.
There were some issues with your array initialization and use of arrays and indexes. I suggest you read a bit more on this because this is important on programming
Finally, a better name for the index variable would be i or index instead of zx.
Try this:
val += array[zx];
You have to use the index of the array.

How to filter squares in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm new in Java coding and I need some help.
I need a method to filter the squares numbers like( 4, 9, 16, 25) from an array, then save them in a new array without replacing the old one.
Unfortunately, I have no approach :/ .
here is some idea by myself:
public static int[] arrayFilter(int originalArray[]) {
int[] filterArray = generateCopy(originalArray);
for(int index = 0; index < filterArray.length; index++) {
}
}
}
I thank you for any help :)
What about this, you iterate over the array and check that the square of the square root is the same as the original number. If so, you add it to a list that you convert to an array once you are done.
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9,10 };
List<Integer> resultList = new ArrayList<>();
for (int number: numbers) {
int sqrRoot = (int) Math.round(Math.sqrt(number));
if (sqrRoot * sqrRoot == number) {
resultList.add(number);
}
}
or if you cannot use a List (see comment of author of the original question, below)...
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9,10 };
int[] initResult = new int[numbers.length];
int numSquares = 0;
for (int i = 0; i < numbers.length; i++) {
int sqrRoot = (int) Math.round(Math.sqrt(numbers[i]));
if (sqrRoot * sqrRoot == numbers[i]) {
initResult[numSquares] = numbers[i];
numSquares++;
}
}
int[] result = new int[numSquares];
for (int i = 0; i < numSquares; i++) {
result[i] = initResult[i];
}
The reason I calculate the square root as follows (int) Math.round(Math.sqrt(numbers[i])) is to prevent floating point arithmetic issues. This way, the square root of the integer 4 will always be an integer with value 2.
Here an example using Streams with a filter to create a new output array.
public class Squares {
public static void main(String... args) {
double[] numbers = {1, 2, 3, 4, 4.4, 100, 2500, 2500.1};
double[] squares = Arrays.stream(numbers)
.filter(Squares::isSquare)
.toArray();
System.out.println(Arrays.toString(squares));
}
private static boolean isSquare(double d) {
double sr = Math.sqrt(d);
return sr - Math.floor(sr) == 0;
}
}

Random arrays with no repetition

I have to create 15 question where only 10 will be display randomly.(10 array over 15 array). I need to make sure that there is no duplication of array during the random process.
public static void main(String() args){
String question_1 = question_One();
//to question 15
String question_15 = question_fifteen();
String [] question = new String [14];
question[0] = question_1;
question[1] = question_2;
//to question 15
question[14] = question_15;
int random = (int) (Math.random()*11);
System.out.print(question[random]);
}
I'd take the array of questions, shuffle it, and then just take the first ten questions form it. Arrays in Java are extremely limited, though, and this would be much easier to do with a proper Collection, e.g., an ArrayList:
// Build the question list:
List<String> questions = new ArrayList<>(15);
questions.add(question_1);
questions.add(question_2);
// etc...
// Shuffle it:
Collections.shuffle(questions);
// Ask the first ten:
List<String> questionsToAsk = questions.subList(0, 10);
EDIT:
The usage of ArrayLists and Collections is just a convenience. The same logic should also stand with arrays, although it will require you to implement some of it yourself:
// Build the question list:
String[] questions = new String[15];
questions[0] = question_1;
questions[1] = question_2;
// etc...
// Shuffle the first 10 elements.
// Although the elements can be taken from indexes above 10,
// there no need to continue shuffling these indexes.
Random r = new Random();
for (int i = 0; i < 10; ++i) {
int swapIndex = r.nextInt(15 - i) + i;
String temp = questions[i];
questions[i] = questions[swapIndex];
questions[swapIndex] = temp;
// Ask the first ten:
String[] questionsToAsk = new String[10];
for (int i = 0; i < 10; ++i) {
questionsToAsk[i] = questions[i];
}

For Loop value assign with multiple String - java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
below are the For Loop
//Declare 5 String variable
String p1, p2, p3, p4, p5;
for (int row = 1; row <= 5; row++) {
String pno = driver.findElement(
By.xpath("//*[#id='body']/table/tbody/tr[" + row + "]/td")).getText();
p1 = pno;
}
my question
while executing the First row (row =1) it should be assign that value in p1 variable
While executing the Second row (row = 2) it should be assign that value in p2 variable
, vice-versa
how could possible to assign the each row value with separate variable in java
you are looking for an array or ArrayList
//in your loop where i is iterator variable
arr[i] = someNewValue;
or if you are not sure how many elements
arrayList.add(someNewValue);
//Declare 5 String variable
String p1, p2, p3, p4, p5;
String[] pArray = new String[5]; // create an array to store values
for (int row = 1; row <= 5; row++) {
String pno = driver.findElement(
By.xpath("//*[#id='body']/table/tbody/tr[" + row + "]/td")).getText();
pArray[row - 1] = pno; // store value to an array
}
// put the values in the array to the Strings originally created
p1 = pArray[0];
p2 = pArray[1];
p3 = pArray[2];
p4 = pArray[3];
p5 = pArray[4];
You can use ArrayList if you want to dynamic sized collection. i.e when you don't know the exact size you would need
ArrayList<String> p = new ArrayList<String>();
for (int row = 1; row <= 5; row++) {
String pno = driver.findElement(
By.xpath("//*[#id='body']/table/tbody/tr[" + row + "]/td")).getText();
p.add(pno);
}
If you know the exact size, then String Array would be sufficient. I see that you have hardcoded the max value conditional statement in your for loop. then, it is evident that you know the exact size you need. Here, you can go for String array as well.
String[] p = new String[5]; // length is 5
for (int row = 1,count=0; row <= 5; row++,count++) {
String pno = driver.findElement(
By.xpath("//*[#id='body']/table/tbody/tr[" + row + "]/td")).getText();
p[count] = pno;
}
Hope you understand now

Remove all occurrences of an integer from an int array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I remove all occurrences of an integer, say, 17 in this example from a given array in java?
I tried setting entries to (Integer) null though it doesn't work.
Input array: [0,6,0,17,1,9,17,8,4]
Output array: [0,6,0,1,9,8,4]
for(int i =0;i<ansa.length;i++){
if(ansa[i]==17)
{
ansa[i]=(Integer)null;
}
}
This results in
Exception in thread "main" java.lang.NullPointerException
int[] array = { 0,6,0,17,1,9,17,8,4 };
int[] filtered = Arrays.stream(array).filter(i -> i != 17).toArray();
System.out.println(Arrays.toString(filtered));
:-)
Try this one.
Integer[] array ={0,6,0,17,1,9,17,8,4};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(array ));
list.removeAll(Arrays.asList(17 ));
array =list.toArray(new Integer[0]);
System.out.println(Arrays.toString(array));
I tried setting entries to (Integer) null though it doesn't work.
Of course it doesn't, because the size of the array isn't changed. In order to do this, some of the defined java collections (in particular, the ArrayList and Iterator classes) can provide you of a better approach.
In pseudocode:
Turn array into a List
Iterate over its elements
If the element is the given number
Remove it
Return the List as an Array
You can fill in the blanks, just remember that you can't actually remove an element from an array, because its size is static.
Note: I'm going for the educational approach.
This seems to work - although I suspect people will post better/more efficient solutions.
public void test() {
int[] before = new int[] {0,6,0,17,1,9,17,8,4};
int[] after = remove(before, 17);
System.out.println("Before: "+Arrays.toString(before));
System.out.println("Aftre: "+Arrays.toString(after));
}
private int[] remove(int[] before, int remove) {
// Work out how long it must be.
int keep = 0;
for ( int i = 0; i < before.length; i++ ) {
if(before[i] != remove) {
keep += 1;
}
}
// Make the new one
int[] after = new int[keep];
// Fill it in.
for ( int i = 0, j = 0; i < before.length; i++ ) {
if(before[i] != remove) {
after[j++] = before[i];
}
}
return after;
}
Thats one possible solution:
int[] array1 = new int[]{0,6,0,17,1,9,17,8,4};
ArrayList<Integer> result = new ArrayList<Integer>();
boolean flag = true;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array1.length; j++) {
if(array1[i]==array1[j]&&i!=j) {
flag = false;
}
}
if(flag) {
result.add(array1[i]);
}
else{
flag = true;
}
}
System.out.println(result);
I think, if you don't want to use an ArrayList, you will have to count how many 17 are in the array and create a new one with ansa.length-count fields
You cannot remove items from an array you are currently using a for loop to cycle through. At the moment you are getting to the end of your array and looking for the next value even though you deleted it. The array length indicator (ansa.length) does not auto update as you are thinking.
You should use List and an iterator to cycle through the list.
You can use then use the .remove function
You are almost done!!
Integer[] ansa = new Integer[] { 0, 6, 0, 17, 1, 9, 17, 8, 4 };
for (int i = 0; i < ansa.length; i++) {
if (ansa[i] == 17) {
ansa[i] = (Integer) null;
}
}
for (Integer integer : ansa) {
System.out.print(integer+","); //0,6,0,null,1,9,null,8,4,
}
You are facing issue, Because you declared primitive I guess like,
int[] ansa = new int[] // Primitive

Categories

Resources