java - I get an extra input space when I run my code -
i run code put in integer, press enter, input space. in input space put in number input space want says "write line". adds numbers put in first input space , input space. please help. (p.s sorry code's format)
my output: write integer (put input here) (put input here) write integer (put input here)
i don't want 2nd input option.
public static void main(string eth[]){ system.out.println("write integer"); scanner input = new scanner(system.in); if (input.hasnextint()){ } else system.out.println("play rules"); scanner input1 = new scanner(system.in); int = input1.nextint(); { system.out.println("write integer"); scanner input2 = new scanner(system.in); int b = input2.nextint(); int answer = (a+b); system.out.println(answer); } } }
the space you're getting logical error in first if
statement. if input.hasnextint()
true, skip on else
call scanner
directly below because not grouped else
statement. also, allows 2 attempts input1
, 1 input2
. therefore, i'd switch while
loop each , create method read in integers instead of duplicating code.
public static void main(string eth[]) { int = readint(); int b = readint(); int answer = (a + b); system.out.println(answer); } private static int readint() { system.out.println("write integer"); scanner input = null; while(!(input = new scanner(system.in)).hasnextint()){ system.out.println("play rules, write integer"); } return input.nextint(); }
Comments
Post a Comment