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?
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);
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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