2

I am taking input for my application using scanner. My code is as follows:

Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO")
if(sc.next().equals("YES")){
   System.out.println("which input? student or teacher name")
   if(sc.next().equals("student")){
      system.out.println("do something");
   }
   if(sc.next().equals("teacher")){
      system.out.println("do something");
   }
}

}else
{
   system.out.println("program will run itseld");
}

Code is working fine but it is asking input twice. Suppose if I enter student it will not proceed but when I enter student again second time my program starts working. I also saw some similar questions on stackoverflow and tried their solutions but I am not able to resolve this. Please help.

corsiKa
  • 76,904
  • 22
  • 148
  • 194
  • 3
    Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – Pavneet_Singh Nov 06 '17 at 05:24
  • There are numerous compilation errors in this... – Jacob G. Nov 06 '17 at 05:26
  • @Pavneet_Singh It's not an exact duplicate. I would not be surprised if there is a question this IS a duplicate of somewhere, but it would probably be difficult to find unless it happened to bubble up to the top of a list miraculously. – corsiKa Nov 06 '17 at 05:28
  • @corsiKa it does explain the behavior about what is happening , due to `sc.next` and i wouldn't have done it but surprisingly we both reacted at the exact time frame – Pavneet_Singh Nov 06 '17 at 05:30
  • @Pavneet_Singh haha down to the second =o – corsiKa Nov 06 '17 at 16:01

2 Answers2

3

sc.next() grabs an input each time. Store this to a variable and just use the variable when comparing.

String input = sc.next();
if(input.equals("YES")) {
    // logic here
}
corsiKa
  • 76,904
  • 22
  • 148
  • 194
0

try something like this

import java.io.*;
import java.util.*;

class SumsInLoopTester {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Do you want to give user input :YES/NO");
        String input = sc.next();
        if (input.equals("YES")) {
            System.out.println("which input? student or teacher name");
            String input2 = sc.next();
            if (input2.equals("student")) {
                System.out.println("do something");
            } else if (input2.equals("teacher")) {
                System.out.println("do something");
            }
        } else {
            System.out.println("program will run itseld");
        }
    }
}
aKilleR
  • 1,166
  • 1
  • 14
  • 19