How to avoid repetition in array filling - java

I have the next code and what I want to do is to check whether I have a value inside an array or not. The problem is, my code does the comparison just between the value I give as a parameter and the last value in the array, what I want to check is to see of I have the value and then return the boolean true, but my code just compare last value in the array. The code is here:
public boolean trueIdTienda(String s) {
boolean f = false;
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())) {
f = true;
} else {
f = false;
}
}
return f;
}

This part is not needed:
else {
f = false;
}
Since if one of them match it is a match, you don't need to set it back to true. Also you could return after a match, to speed the code up a bit (and more logical).
If you let the else part stay there, it will set the value back to false once it find a non-equal. Consider finding [1, 2] for 1 and you will see.

This is a classic search algorithm:
public boolean trueIdTienda(String s) {
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())){
return true;
}
}
return false;
}

Your function can be simplified to immediately return true if the value is found.
public boolean trueIdTienda(String s) {
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())) {
return true;
}
}
return false;
}

Maybe you can use a Collection. something like a Hash should help you
http://www.java2s.com/Tutorial/Java/0140__Collections/Createuniquelistsofitems.htm

The problem is that although you find that a value in the array is equal to the argument you set the boolean true and continue comparing with other values which return the boolean to false.
Final value of the boolean is the result of comparing with the last value, what solves the problem is to add break; after f=true;
Try to understand what caused your problem not simply using a correct code.

Related

I don't understand how returns work with if/else statements involved -please help [java] [duplicate]

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 1 year ago.
here is my code. I am simply wanting to return the int value if it matches if not I don't want to return anything but it keeps giving me errors saying that I need to add a return statement to my code. I'm new to Java so I don't quite understand why it's not working.
Any help you can provide would be greatly appreciated,
public int faceIndex(String currentWheelFace) {
for (int i = 0; i < wheelFaces.length; i++) {
if (wheelFaces[i] == currentWheelFace) {
return i;
}
}
}
Should be like this
You should have a return statement outside loops
public int faceIndex(String currentWheelFace) {
int number;
for (int i = 0; i < wheelFaces.length; i++) {
if (wheelFaces[i] == currentWheelFace) {
number = i;
break;
}
}
return number;
}
In your code, the return breaks out of the method as soon as the condition is satisfied.
But if it falls through by exhausting the for loop, then there is no return value provided. That will generate a compile error, needing a return value.
So, provide a default return value and then the calling code can check for validity. You would have to document the range of values of valid returns, but it seems that returning -1 could indicate the value is not found.
The problem is that, if ur condition fails, the function will return nothing, then it will become a void function instead of int. Also your return statement is inside a loop, which means that ur function will return more than one value if WheelFaces[i] becomes equal to CurrentWheelFace more than once.... If u dont want ur function to do that then just add a break statement:
public int faceIndex(String currentWheelFace) {
int W;
for (int i = 0; i < wheelFaces.length; i++) {
if (wheelFaces[i] == currentWheelFace) {
W=i;
break;
}else{
W=//some other default int value;
break;
return W;
}
}
}

I want to count 4 boolean from an object and return a count of how many are true

I have a User object which has the Boolean values of workOut1, workOut2, workOut3, workOut4
I want to create a method to return a count of how many are true.
Example
Workout1 = false
Workout2 = true
Workout3 = false
Workout4 = false
would return 1.
Any help would be appriciated
You can do something like this:
long numberOfTrues = Stream.of(workout1, workout2, workout3, workout4)
.filter(w->w)
.count();
Even for only 4 variables it would make sense to put them in an array or list.
If there are more you must do it and iterate and sum over the array, or use filtering of the list.
Now for 4 variables you can use the ternary operator:
int counter = (Workout1 ? 1 : 0) + (Workout2 ? 1 : 0) + (Workout3 ? 1 : 0) + (Workout4 ? 1 : 0);
Not elegant though.
Put everything in an Array and then create a new method to iterate through the array. The method will check every boolean value inside the array and check if it's true. If it's true then the int x will be incremented by 1. Once the loop is done, it will return the value of x. Hope it helps!
public static void main(String[] args) {
Boolean[] test = new Boolean[4];
boolean Workout1 = false;
boolean Workout2 = true;
boolean Workout3 = false;
boolean Workout4 = false;
test[0] = Workout1;
test[1] = Workout2;
test[2] = Workout3;
test[3] = Workout4;
System.out.println(check(test));
}
public static int check(Boolean[] array) {
int x = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(true)) {
x++;
}
}
return x;
}

Issue with my string reverse program

newer programmer here, having trouble diagnosing the issue with my string reversal program. The program is supposed to compare two strings and find out if string x is the reversal of string y and if it is it returns true, if not it returns false.
public class Reverse
{
public static void main(String[] args)
{
System.out.println(isExactReverse("ba", "a"));
System.out.println(isExactReverse("desserts", "stressed"));
System.out.println(isExactReverse("apple", "apple"));
System.out.println(isExactReverse("regal", "lager"));
System.out.println(isExactReverse("war", "raw"));
System.out.println(isExactReverse("pal", "slap"));
}
public static boolean isExactReverse(String x, String y)
{
//To be completed
int counter = 0;
int temp = x.length() - 1;
boolean result = false;
for(int i = 0; i < y.length(); i++)
{
if(x.charAt(temp) == y.charAt(i))
{
counter++;
}
temp--;
}
if(counter == y.length())
{
result = true;
}
return result;
}
}
the output i get is not correct and I am getting a runtime error.
true
true
false
true
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:658)
at Reverse.isExactReverse(Reverse.java:24)
at Reverse.main(Reverse.java:11)
Expected output:
False
True
False
True
True
False
The problem in your code is that it assumes that x and y have the same length. When it is not so, the code either returns a false positive, as in case of "ba"-"a", or crashes, as in case of "pal"-"slap".
Fix this by adding this check at the top of your isExactReverse method:
if (x.length() != y.length()) {
return false;
}
Demo.
The code is certainly able to be compiled. It would be nice if you could specify the problem.
But I guess you got problems getting the correct result. First of all, I would recommend you simplified the code. There is a lot of lines, that don't have to be there.
Here is, what I would do.
public class Reverse
{
public static void main(String[] args)
{
System.out.println(isExactReverse("ba", "a"));
System.out.println(isExactReverse("desserts", "stressed"));
System.out.println(isExactReverse("apple", "apple"));
System.out.println(isExactReverse("regal", "lager"));
System.out.println(isExactReverse("war", "raw"));
System.out.println(isExactReverse("pal", "slap"));
}
public static boolean isExactReverse(String x, String y)
{
//To be completed
int temp = x.length() - 1;
boolean result = false;
for(int i = 0; i < y.length(); i++)
{
if(!x.charAt(temp).equals(y.charAt(i)))
{
return false;
}
temp--;
}
return true;
}
}
This should work. I don't really have an answer for your post, because I don't know you problem, but this is just some kind of help that maybe will resolve your problem.

return int from within if statement in a loop in java

i have a loop which iterates equal to the length of an array, inside this loop i have a method which do some processing and have if-else structure inside. i want that if certain condition is true, then re-iterate the whole loop else continue.
the Minimum working code is provided.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
fp.factprocess(fact, rule, vars, cons);
}
contents of fp.factprocess are like
if(condition==true)
make xx = 0 in the parent loop
else
continue
i dont know how do i do it, i used return statement but it has to be in the end and can not be in the if-block.
Return a boolean from the condition test. If boolean true, set xx to -1 (to be incremented to 0) in the loop.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
boolean setXXtoZero = fp.factprocess(fact, rule, vars, cons);
if(setXXtoZero) xx=-1;
}
fp.factprocess:
return condition;
Yes, there can be a return statement in the if block.
public int getValue(int val){
if ( value == 5 ){
return value;
}
else{
return 6;
}
}
for instance, is valid Java code.
public int getValue(int input){
if ( input == 5 ){
return input;
}
}
on the other hand, is not, since you don't return anything if input does not equal 5, yet the method has to either return an int, or throw an Exception.
That's probably what your problem is: you need to provide a return statement for all possible scenario's.
If you want to modify the xx variable of the loop, I suggest to return a boolean in your factprocess method.
for (int xx = 0; xx < temp.length; xx++) {
rule = temp[xx][1];
cons = temp[xx][2];
boolean shouldRestart = fp.factprocess(fact, rule, vars, cons);
if (shouldRestart) {
xx = 0;
}
}
Pass xx to factprocess() and assign the return to xx
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
xx = fp.factprocess(fact, rule, vars, cons, xx);
}
Inside factprocces()
if (condition == true) {
return 0
} else {
return xx
}

java Recursion row

i'm getting lost, could someone of you please help me?
i want my function "oddEvenRow" to check if the values in row index 0,2,4 are odd. if so return true, if not return false
this is the code i wrote :
public class Matrix
{
public static int temp=0;
public static boolean oddEvenRow (int[][]a, int r, int c, int count)
{
if(r>4&&count==12) {
temp=1;
return false;
}
if(a[r][c]%2==0) {
temp=1;
return false;
}
else {
count++;
if(c==3)
oddEvenRow(a,r+2,0,count);
else
oddEvenRow(a,r,c+1,count);
return true;
}
}
public static void main(String args[])
{
int r=0;
int c=0;
int count=0;
int[][]a=new int[5][4];
a[0][0]=1;
a[0][1]=3;
a[0][2]=7;
a[0][3]=15;
a[1][0]=4;
a[1][1]=15;
a[1][2]=2;
a[1][3]=9;
a[2][0]=11;
a[2][1]=21;
a[2][2]=1;
a[2][3]=45;
a[3][0]=8;
a[3][1]=15;
a[3][2]=8;
a[3][3]=12;
a[4][0]=7;
a[4][1]=3;
a[4][2]=25;
a[4][3]=21;
System.out.println(oddEvenRow(a,r,c,count));
}
}
[Looking at your code, i suspect you meant your question to say "if ALL values in rows 0,2, and 4 are odd..."]
Anyway, you're setting the short circuit variable 'temp' but never using it. Try adding a check to the top of your function...
if(temp == 1)
return false;
For me the part with count is redundant as you are checking all rows in r variable - after the last significant row (4th) the method will return. You do not need checking if there were 12 numbers checked.
What is more temp variable acts as return value in your code which you are actually returning with the method itself - also redundant.
I do not see the point in checking already defined number of values using recursion but if you need so consider the following:
public static boolean oddRow(int[][] a, int r, int c) {
//checking if we checked all rows
if (r > 4) {
return true;
}
//checking if all columns in row were checked and moving to r+2 row
if (c > 3) {
return oddRow(a, r + 2, 0);
}
//checking if current value is odd - if yes, keep checking the rest / if not, return false
return (a[r][c] % 2 == 0) ? oddRow(a, r, c + 1) : false;
}

Categories

Resources