How can I make a program get a variable inside a loop? (java) -
i making program asking age isn't working. first asks how old are, scanner module , puts age inside variable. want output @ end age, needs int, if put string or else gives error:
exception in thread "main" java.util.inputmismatchexception @ java.util.scanner.throwfor(unknown source) @ java.util.scanner.next(unknown source) @ java.util.scanner.nextint(unknown source) @ java.util.scanner.nextint(unknown source) @ org.asking.age.main(asking.java:18)
i want let him instead of error): please enter number between 1 , 100, if enter else number between 1-100. , if put in wrong number has 'restart', , if number has end.
i tried loop:
(i = age scanner)
while(i>100 || i>0) { if (a < 100 || > 0) { system.out.println("please enter number between 1 , 100"); system.out.println("how old you?"); scanner s = new scanner(system.in); int = s.nextint(); { system.out.println("you " + + "years old") }}}}}
but @ beginning 'if' cant reach variable. there exist another/any way this?
thanks helping, , sorry bad english :)
thanks @thelostmind helping got code :
but dont understand how use if(>0 && <100, , matches isn't working
public static void main(string[] args) { system.out.println("how old you?"); scanner h = new scanner(system.in); string a= h.nextline(); string str = a; string matches=("\\d+"); integer.parseint(a); { { system.out.println("please enter number between 1 , 100"); system.out.println("how old you?"); h.nextline(); } while(a>0 && a<100); } } }
first of all, start decalring both
scanner
,int a
outside loop.next, use
scanner#nextline()
read entire line of input string.then use
string#matches("\\d+")
,integer.parseint(inputstring)
parse int number.then use
if(>0 && <100)
check.
there methods in scanner
class (hasnextint()
) wait int, that's not looking for.
Comments
Post a Comment