'I got inputMissMatch exception during my TCS exam
public class Solution {
public static void main(String args[])
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
int input1=sc.nextInt();
sc.nextLine();
String str1=sc.nextLine();
Double input2=sc.nextDouble();
}
}
}
This is my code. I only got this exception in "int" and "double" input only in for loop. IF I write it out-side of for loop it working fine. Please any one can help me solve this problem, because I am getting this error in my TCS exam.
Solution 1:[1]
Unfortunately your question does no give me much information, however I will try to answer anyway (need that rep). Im assuming the issue you run into is a InputMismatchException ? This is probably something to do with you trying to pass a double (i.e. 12.0) into an int. Using something like System.out.println("Enter Int Input:") can help you highlight which input type you should be providing on the line. try/catch blocks can stop the error being thrown.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
for (int i = 0; i < 5; i++) {
System.out.println("i: " + i);
System.out.println("Enter Int Value:");
int input1 = sc.nextInt();
sc.nextLine();
System.out.println("Enter String Value:");
String str1 = sc.nextLine();
System.out.println("Enter Double Value:");
Double input2 = sc.nextDouble();
}
} catch (InputMismatchException e) {
System.out.println("Invalid input entered for variable type.");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lew |
