Home > other >  Trying to find a certain string in an array and assign it a val using for/if statements
Trying to find a certain string in an array and assign it a val using for/if statements

Time:03-10

I have an array of 5 cards in deck but I'm trying to use a for statement to search the values and pick out a value then assign it a value of 10. Below is my code:

for(i = 0; i < hand1.length; i  ){
  if(hand1[i] == "D4"){
    int val = 10;
  }
}
System.out.println("The value is: "   val);

Please let me know what the issue is. Thanks in advance.

CodePudding user response:

You construction is correct, but the visibility of the int val = 10 statement will not be visible outside of the if code block. To solve that, you need to declare the int val variable before the for loop.

CodePudding user response:

You are declaring the val variable inside of the if block, so its scope is limited to just that block, and so it cannot be seen outside of the loop. You need to move the declaration of the variable outside of the loop, eg:

int val = 0;
for(i = 0; i < hand1.length; i  ){
  if(hand1[i] == "D4"){
    val = 10;
  }
}
System.out.println("The value is: "   val);
  • Related