Sunday, June 30, 2019

incompatible types required: int found: java.lang.String (basic programming)



I have come across this error a few times, and I try many things to fix it, but I can't seem to find out what is going wrong. here is the code:




import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String name1 = scan.nextLine();
String name2 = scan.nextLine();
int num1 = scan.nextLine();
double num2 = scan.nextLine();


System.out.println("Employee Name:" + name2 + name1);
System.out.println("Age:" + num1);
System.out.println("Salary:" + (double)num2);
}
}


And the error that shows up specicfically is:





[File: /InputExample.java Line: 9, Column: 25] incompatible types required: int found: java.lang.String



[File: /InputExample.java Line: 10, Column: 28] incompatible types required: double found: java.lang.String



Answer



You're reading in a String, but want to save it as Integer/Double. Try this:



int num1 = Integer.valueOf(scan.nextLine());



Same goes for Double.



Or as OldCurmudgeon mentioned:



int num1 = scan.nextInt();

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...