how to compare int[] array with int in android? - java

I need to compare int[] array with integer values. This code am having
int c1[], c2[], c3[];
int count1=0, count2=1, count3=0;
c1 = new int[] { count1 };
c2 = new int[] { count2 };
c3 = new int[] { count3 };
Now i need to compare this int[] array with int, that is any array equals 0 then code don't need to execute if not equals then code execute. How to compare ?? help me thanks in advance ? this if condition i tried but it wont execute exactly.
if(c1.equals(0))
{
// skip
}
else
{
// execute code
}
this above code didn't work.

Try following:
for(int i=0;i<cl.length;i++){
if(c1[i]==0)
{
// skip
}
else
{
// execute code
}
}

Perhaps you are looking for :
if(c1[0] == 0)
{
// skip
}
else
{
// execute code
}
Though it's unclear why you need c1 to be an array if it only holds a single integer.

Use c1[0],c1[1] .... and (iterate through loop)
like-
if(c1[0]==0)

Related

JAVA: What am I doing wrong?

I am trying to determine the Hamming distance between two arrays of ints. Pre: aList != null, bList != null, aList.length == bList.length; Post: return the Hamming Distance between the two arrays of ints. I am not sure what I am doing wrong, I am just now starting to learn how to code. Any help is appreciated. Thanks in advance :)
Here is my code:
public class test {
public static int hammingDistance(int[] aList, int[] bList) {
// check preconditions
if (aList == null || bList == null || aList.length != bList.length)
throw new IllegalArgumentException("Violation of precondition: " +
"hammingDistance. neither parameter may equal null, arrays" +
" must be equal length.");
//Starting a counter
int counter = 0;
System.out.println("test");
//checking to see if there is a mismatch in the values of the two given arrays
for (int i = 0; i < bList.length; i++) {
if (bList[i] != aList[i]) {
//increasing counter everytime there is a mismatch
counter++;
}
}
return counter;
}
public static void main(String[] args) {
int[] aList = { 1,3,3,4 };
int[] bList = { 1,2,10,4 };
System.out.println(hammingDistance(aList, bList));
}
}
Updated Code
You are resetting the counter to zero whenever there is a match. So counter in never effective. Remove the else part of the code.
You are resetting the counter when two elements are equal (see your else statement). You shouldn't be doing anything when two called are equal.
Hope it helps,

function.Function as parameter in print method

I dont have any clue how to approach the problem i am facing. We have to print out an array using function.Function as a parameter and using lambas to print out 1. the even and 2. the odd numbers.
final class Main
{
private Main() {}
public static void main(String[] argv)
{
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
// Even
ds.print(..);
}
// Odd
ds.print(...);
}
// end of main class
import java.util.Arrays;
import java.util.function.Function;
class DataStructure
{
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
int getSize()
{
return SIZE;
}
int[] getInts()
{
return arrayOfInts;
}
DataStructure()
{
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++)
{
arrayOfInts[i] = i;
}
}
private DataStructureIterator getIterator(IteratorStrategy strategy)
{
return strategy.getIterator(this);
}
void print(IteratorStrategy strategy)
{
DataStructureIterator iterator = getIterator(strategy);
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
}
void printEven()
{
// Print out values of even indices of the array
DataStructureIterator iterator =
getIterator(newEvenIteratorStrategy());
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
}
//this method is still missing - we have to use the given parameters
void print(java.util.function.Function <Integer,Boolean> iterator)
{
}
}
The expected output is for isEven 0 2 4 6 8 10 12 14
and for isOdd 1 3 5 7 9 11 13
The rest of the given class shouldn't be important atleast i think so.
I am searching for solutions or just a hint for hours but I dont find anything useful. Your help is much appreciated and sorry for my english
If you need anything let me know. Btw I am new to stackoverflow so I hope I did everything right
Not sure that I understood what you really wanted but maybe you should have
a look at this link: https://www.boraji.com/java-8-javautilfunctionfunction-example.
It explains how to use the Function interface and gives an example with even and odds number...
In your case, Function<Integer, boolean> means that you are going to receive an Integer as input and that you must return a boolean (I suppose true if even and false if odd).
Hope it helps! ;)

How to print the index of an array into separate ArrayList

I have created a method for my program, where I compare two arrays, user and test. I am trying to add the index of the array user into the ArrayList qMissed when it is not the same as the test Array.
If both arrays are the exact same then it should just return null.
I am getting exception errors because I need to complete the reference type but I am unsure of what to do.
/**
* #param user
* #param test
* #return
*/
public static ArrayList<String> questionMissed(String[] user, String[] test)
{
ArrayList<int> qMissed = new ArrayList<int>();
for (int i = 0; i <= user.length-1; i++)
{
if (user[i] != test[i])
{
qMissed = Arrays.asList(qMissed).indexOf(user);(i+1);
}
else if (user[i] == test[i])
{
return null;
}
}
return qMissed;
}
Your method seems to have some logical and compilation issues.
Looks like you need this method,
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<Integer>();
for (int i = 0; i < user.length; i++) {
if (!user[i].equals(test[i])) {
qMissed.add(i);
}
}
return qMissed.size() == 0 ? null : qMissed;
}
Fixes and their explanation,
1. Your return type has to be List<Integer> instead of ArrayList<String> because you want to return an ArrayList of Integer indexes and not string.
2. Second problem you can't use primitive type in ArrayList<int> instead you need to use ArrayList<Integer>
3. You can't compare strings with == instead you need to use equals method on string.
4. You don't have to return null inside forloop else hence else block I have removed.
5. After you exit the forloop, as you want to return null if both element's arrays matched hence this code,
return qMissed.size() == 0 ? null : qMissed;
Let me know if you face any issues using this method.
Edit:
How to display "All are correct" message in case both passing arrays have same numbers. You must be calling it something like this,
List<Integer> list = questionMissed(user,test);
if (list == null) {
System.out.println("All are correct");
} else {
// your current code
}
You can try changing the return type from ArrayList to ArrayList in the method:
public static ArrayList<int> questionMissed(String[] user, String[] test) {
ArrayList<int> qMissed = new ArrayList<int>();
for (int i=0;i<=user.length-1;i++) {
if (user[i] != test[i]) {
qMissed = Arrays.asList(qMissed).indexOf(user);(i+1);
} else {
return null;
}
}
return qMissed;
}
Also you can remove the else if condition cause is redundant. Please attach the exceptionsyou are getting.
I see multiple issues with your code, Firstly as Andreas said ArrayList cannot host primitive types
so change it to
ArrayList<Integer> qMissed = new ArrayList<Integer>();
Second problem I see is that you are comparing Strings using == this compare can be wrong so use equals instead
(user[i].equals(test[i]))
and the last mistake I see is the code cannot be compiled, can you give me more information in the comments to what you are trying to do in this part since It's not valid code
qMissed = Arrays.asList(qMissed).indexOf(user);
(i + 1);
if you want to do something like Pushpesh Kumar Rajwanshi answer you can use java 8 streams what this does is makes an IntStream with the length of user, and then filters it to have only items if they don't equal at the same index and then adds it to qMissed.
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<>();
IntStream.range(0, user.length)
.filter(i -> !user[i].equals(test[i]))
.forEach(qMissed::add);
return qMissed.size() == 0 ? null : qMissed;
}
I guess you want like below ..
public static ArrayList<Integer> questionMissed(String[] user, String[]
test) {
ArrayList<Integer> qMissed = new ArrayList<Integer>();
int i = 0;
if(user.length == test.length ) {
while(i < user.length ){
if (!(user[i].equals(test[i]))) {
qMissed.add( i + 1);
}else {
return null;
}
i++;
}
if(user.length > 0 && i == user.length ) {
return qMissed;
}
}
return null;
}

Incorrect logic in my loop

public static void main(String[] args) {
Integer[] courses1 = {1,2,3};
Integer[] courses2 = {0,1};
Integer[] longestArr;
Integer[] shortestArr;
ArrayList commonCourses = new ArrayList();
if ( courses1.length > courses2.length)
{
longestArr = courses1; shortestArr = courses2;
}
else
{
longestArr = courses2; shortestArr = courses1;
}
for ( int i : longestArr)
{
for ( int j : shortestArr)
{
if (i == j);
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}
No matter what the values of course1 and courses2, the arrayList commonCourses always has a size of one more the the total number of elements in both arrays when it is supposed to only contain the elements that are in both arrays. I have 2 questions why is ever element from the 2 arrays being added to the arrayList and why is the size of the arrayList always one more than the total number of elements? If you are wondering why I have courses1 and courses2 declared at the start, this is a problem from talentBuddy.co that I'm testing on eclipse. I have tested with different starting conditions and the same thing always happens.
My new slimmed down solution
public static void main(String[] args) {
Integer[] courses1 = {1};
Integer[] courses2 = {0};
ArrayList <Integer>commonCourses = new ArrayList<Integer>();
for ( int i : courses1)
{
for ( int j : courses2)
{
if (i == j)
commonCourses.add(i);
}
}
Collections.sort(commonCourses);
System.out.println(commonCourses.size());
}
Your problem is the semicolon in this line:
if (i == j);
The if clause ends here and the following line is always executed.
The semi-colon at the end of the if-condition is your problem. For a detailed explanation on why this happens, see this StackOverflow post. In short, the semi-colon causes the compiler to ignore the conditional at runtime.
for ( int j : shortestArr)
{
if (i == j);
// ^ Remove this semi-colon
commonCourses.add(i);
}
Using curly-braces to format your if-statements helps prevent this from happening:
if(condition){
doSomething();
}
for ( int j : shortestArr)
{
if (i == j);
// ^ REMOVE THIS SEMICOLON
commonCourses.add(i);
}
The problem is that extra semicolon. Your chunk of code is functionally identical to this right now:
for ( int j : shortestArr)
{
if (i == j)
{
}
commonCourses.add(i);
}
You have a misused semicolon after the if condition.
if (i == j);
I have never worked in a firm where they did not require parenthesis after if:
if (...) {
...
}
And the reason quite evident.
Let me show the most abstracted solution:
Courses are sets of unique course numbers
Common courses is an intersection set
In java one uses abstract interfaces like Set for the variable, but can implement that set with different implementing classes
One wants a sorted set, TreeSet is such an implementation
Set<Integer> courses1 = new HashSet<>();
Collections.addAll(courses1, 1, 2, 3);
SortedSet<Integer> courses2 = new HashSet<>();
Collections.addAll(courses2, 0, 1);
SortedSet<Integer> commonCourses = new TreeSet<>(courses1);
commonCourses.retainAll(courses2);

java.lang.ArrayIndexOutOfBoundsException: 4 Error

I'm new to coding and I've been writing this code and trying to make it work but every time I run it it crashes. I've looked things up and will writing this code I've followed java's website on how to properly write down code as well as this site.
Anyways, it would be greatly appreciated if someone can explain to me why this is not working because it seems to me like the logic is there but I don't get why it crashes.
My code:
import java.util.Scanner;
import java.lang.String;
import java.util.*;
public class Question1
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
System.out.println("Enter either letters or numbers and I'll magically tell you if they are consecutive :D");
String inputedString= keyboard.nextLine();
boolean consecutiveOrNot=isConsecutive(inputedString);
System.out.println("Drum rolls...... Is it consecutive: "+ consecutiveOrNot); //Problem with this line?
}
public static boolean isConsecutive(String inputedString)
{
//Storing string's units into an array and converting to UpperCase if necessary
//and storing string's numerical value into the variable 'arrayCharToInt'
char[] charIntoArray= new char[inputedString.length()];
int[] arrayCharToInt= new int[inputedString.length()];
for (int i=0;i<inputedString.length();i++ )
{
charIntoArray[i]=inputedString.charAt(i);
if (Character.isLetter(charIntoArray[i]) && Character.isLowerCase(charIntoArray[i]))
{
charIntoArray[i]= Character.toUpperCase(charIntoArray[i]);
}
arrayCharToInt[i]=(int) charIntoArray[i];
}
// The next if statements and the methods that they call are used to verify
//that the content of the initial string is either letters or numbers, but not both together
boolean[] continuous= new boolean[arrayCharToInt.length];
boolean[] testContNumbersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContNumbersIncreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersIncreasing= new boolean[arrayCharToInt.length];
Arrays.fill(continuous, true);
if (lowestValue(arrayCharToInt)>=65 && highestValue(arrayCharToInt)<= 90)
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContLettersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -25));
testContLettersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -25));
}
return (Arrays.equals(continuous,testContLettersIncreasing) || Arrays.equals(continuous,testContLettersDecreasing));
}
else if ((lowestValue(arrayCharToInt) >= 48) && (highestValue(arrayCharToInt)<= 57))
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContNumbersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -9));
testContNumbersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -9));
}
return (Arrays.equals(continuous,testContNumbersIncreasing) || Arrays.equals(continuous,testContNumbersDecreasing));
}
else
{
return false;
}
}
public static int lowestValue(int[] array)
{
int lowest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( lowest>array[counter])
lowest= array[counter];
}
return lowest;
}
public static int highestValue(int[] array)
{
int highest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( highest<array[counter])
highest= array[counter];
}
return highest;
}
}
The main method seems to be fine because it put everything in the isConsecutive method as a comment except for 'return true;' and indeed the program ran and printed true. So I know the problem lies somewhere in the second method.
If there's anything that I did not do right please tell me and that would be greatly appreciated. After all I'm still learning.
Thanks
All of your calls to arrayCharToInt[x+1] are going to go out of bounds on the last iteration of the loop they're in (for example, if arrayCharToInt.length equals 5, the highest that x is going to go is 4. But then x+1 equals 5, which is out of bounds for an array with five cells). You'll need to put in some sort of if( x == arrayCharToInt.length - 1) check.
in the method isConsecutive inside the for loop: for (int x=0;x<arrayCharToInt.length ;x++ ) , you have used arrayCharToInt[x+1]
if the arrayCharToInt lenth is 4 , then you have arrayCharToInt [0] to arrayCharToInt [3].
now consider this statement:arrayCharToInt[x+1]
when x is 3 this statement will evalueate to arrayCharToInt[4] resulting in array index out of bounds exception
This error throw when something went wrong in the Array calling function.
You got the length and make it print.
for eg:
int a[] = {1,2,3,4}
Length of this array is,
int length = a.length
So length = 4 but highest index is 3, not 4. That means index of the array started with 0. So you have to print:
arr[length-1];
In your program,
x == arrayCharToInt.length - 1

Categories