Java编译错误求助:int无法转换为String类型问题
Hey there! As a fellow Java learner, I totally get how confusing these type mismatch errors can feel when you're just starting out. Let's break down exactly what's going on here and how to fix it.
What's Causing the Error?
The error message Sorting_2.java:25: error: incompatible types: int cannot be converted to String is spelling it out clearly: you’re trying to pass an integer value (either age or roomNum, since those are the obvious numeric fields here) into a parameter spot where the Sorting class’s constructor expects a String.
Looking at your error line:
Sorting sorting = new Sorting(lastName, firstName, age, insuranceCompany, roomNum);
Either age, roomNum, or both are int variables, but your Sorting class’s constructor is defined to accept a String in that parameter position.
How to Fix It
You’ve got two simple, straightforward options to resolve this:
Option 1: Convert the int to a String when creating the object
If the Sorting class’s constructor is supposed to take Strings for those fields, turn your integer values into Strings using one of these easy methods:
String.valueOf(yourIntVariable)Integer.toString(yourIntVariable)
Your corrected line would look like this (assuming both age and roomNum are ints):
Sorting sorting = new Sorting(lastName, firstName, String.valueOf(age), insuranceCompany, String.valueOf(roomNum));
Option 2: Update the Sorting class to accept ints for those fields
If age and roomNum are meant to be numeric values in the Sorting class, adjust the class variables and constructor to use int instead of String:
First, update the class member variables:
public class Sorting { public String lastName; public String firstName; public int age; // Changed from String to int public String insuranceCompany; public int roomNum; // Changed from String to int // ... rest of your class code }
Then update the constructor to match the new types:
public Sorting(String lastName, String firstName, int age, String insuranceCompany, int roomNum) { this.lastName = lastName; this.firstName = firstName; this.age = age; this.insuranceCompany = insuranceCompany; this.roomNum = roomNum; }
Quick Tip for New Java Devs
When you hit type mismatch errors, always double-check two things:
- The data type of the variables you’re passing into a method or constructor
- The data type that the method/constructor is expecting for each parameter position
If you’re still stuck, sharing the full Sorting class code would help narrow things down even more!
内容的提问来源于stack exchange,提问作者Samuel Fipps

