Link to home
Start Free TrialLog in
Avatar of Sarbjyot Singh
Sarbjyot Singh

asked on

Trouble with using Scanner methods nextInt() and nextLine() Together

I am using Scanner methods nextInt() and nextLine() for reading input.

I want my program to work for two inputs

Input 1:

10000 A

Output 1:

17600

 Input 2:
 
 10000
 
 A

Output 2:

17600

This Code is working for Input 1 only and giving Error in Input 2  After I Enter 10000. It is not taking A in next Line And executing program before taking A in Input 2. I want this program to work on both type of inputs.
how can i do that?

    import java.util.Scanner;
    
    public class Main {
    
    	public static void main(String[] args) {
    		Scanner s = new Scanner(System.in);
    		int sal = s.nextInt();
    		
    
    
    		double hra = sal*20.0/100;
    		double da = sal*50.0/100;
    		double pf = sal*11.0/100;
    		String str = s.nextLine();
    		char c = str.charAt(0);
    		int allow = 0;
    		if(c=='A') {
    			 allow = 1700;
    		}else if(c=='B') {
    			allow = 1500;
    		}else {allow = 1300;}
             double t = Math.round(sal + hra + da + allow - pf);
    		 int ts = (int)t;
    		 System.out.println(ts);
    
    	}
    
    }

Open in new window

SOLUTION
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Consider me named, shamed and totally rehabilitated in the paths of righteousness, for I have sinned. I know never to say “please” again, O mccarl.
Here is an example of putting the nextLIne() call in a do...while loop.
Yes, but that again makes no sense - there's no user input prompt
Also, nextLine is being used in that example in quite a different way (in a loop). So quite confusing without comment on that