java - How to write while loop condition -
the program asks password , enter it, else 3 attempts , if fail 3 times locks (in theory).
questions:
how should write while loop, says "line can't resolved variable" , don't know how solve this.
the subtraction of attempts doesn't work. how should write it?
here's code:
import java.util.scanner; public class application { public static void main(string[] args) { while(line != correctpass) { string correctpass = "java"; system.out.println("enter password"); scanner input = new scanner(system.in); string line = input.nextline(); if(line.equals(correctpass)) { system.out.println("wellcome sir!"); break; } else { int num = 3; system.out.println("wrong password, please try again! " + num + " attempts left!"); num = num - 1; if(num == 0) { system.out.println("system locked!"); break; } } } } }
the variables line , correctpass declared inside loop, hence condition statement not have access variables, should declared , initialized outside loop.
it this:
public class application { public static void main(string[] args) { string correctpass = "java"; scanner input = new scanner(system.in); int num = 3; system.out.println("enter password"); string line; while (num != 0 && !(line = input.nextline()).equals(correctpass)) { system.out.println("wrong password, please try again! " + num + " attempts left!"); num = num - 1; system.out.println("enter password"); } if (num == 0) { system.out.println("system locked!"); } else { system.out.println("wellcome sir!"); } } }
Comments
Post a Comment