-3

I want to create a public string variable in a for loop that I can use even outside of it.I know that this is possible in C# just by marking the string as public, bt doing the same thing in Java doesn't seem to do the trick. Any suggestions?

for (int i = 0; i < answerList.size(); i++) {
    System.out.println(answerList.get(i).q);
    answerList.get(i).spot = i;
    System.out.println(answerList.get(i).spot);
    switch (answerList.get(i).spot) {
        case 0:
            if(answerList.get(i).correct = true) {
                String correctAns = "a";
                String correctAnsVariantTwo = "A";
                break;
            }
        case 1:
            if(answerList.get(i).correct = true) {
                String correctAns = "b";
                String correctAnsVariantTwo = "B";
                break;
            }
        case 2:
            if(answerList.get(i).correct = true) {
                String correctAns = "c";
                String correctAnsVariantTwo = "C";
                break;
            }
        case 3:
            if(answerList.get(i).correct = true) {
                String correctAns = "d";
                String correctAnsVariantTwo = "D";
                break;
            }
    }
}
Scanner a = new Scanner(System.in);
String ats = a.nextLine();
if(ats.equals(correctAns)) {
    //do something
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

1

What you can do is declare that variable outside the loop, even if it's empty, and give it a value when you need it (it's better to do so at the beginning, but it's valid to do it on the loop. It's what I do when I need to do things with a variable inside and outside a loop.

0

I declared the string outside of the switch statement, everything works now.