2014-11-05 25 views
0

请帮助找到我的代码是“不兼容的类型”....我看了看,看,看,无法找到它任何地方。我在这里得到一个“不兼容的类型”的错误,我不明白为什么

import java.util.Scanner; 

public class Years 
{ 
    private int centuries, decades; 

    public Years(int years) 
    { 
     centuries = years/100; 
     years -= 25 * years; 
     decades = years/10; 
     years -= 10 * years; 
    } 
    public int getCenturies() 
    { 
     return centuries; 
    } 
    public int getDecades() 
    { 
     return decades; 
    } 
    public static void main(String[] args) 
    { 
     int years; 

     if(args.length >= 1) 
     { 
      years = Integer.parseInt(args[0]); 
     } 
     else 
     { 
      Scanner keyboard = new Scanner(System.in); 
      System.out.print("Enter the amount in years: "); 
      years = keyboard.nextInt(); 
      keyboard.close(); 
     } 

     Years y = new Years(years); 
     System.out.println(years = "y =" + 
     y.getCenturies() + "c +" + y.getDecades() + "d"); // I am getting the error right here. 
     } 
} 
+1

你应该把你在哪里得到的错误,而不是错误本身 – Jay 2014-11-05 19:16:05

+0

我用一个评论,以显示错误是在哪里......错误是朝着程序的底部。 – 2014-11-05 19:18:47

+0

如果你看看System.out.println('年= =“y =”'+,那里有一个串联的问题 – 2014-11-05 19:22:54

回答

3
System.out.println(
    years = "y =" + y.getCenturies() + "c +" + y.getDecades() + "d" 
); 
// ^^^^^^^ 

问题是years =。编译器不确定该怎么做。 =右侧的结果是一个字符串,因为您正在执行字符串连接。

所以编译器认为你这样做:

years = ("y =" + y.getCenturies() + "c +" + y.getDecades() + "d") 

years是int所以这不是一个有效的表达。

你可能只是意味着这样的:

System.out.println(
    "y = " + y.getCenturies() + "c + " + y.getDecades() + "d" 
); 

或者可能在那里的地方串联years

System.out.println(
    years + "y = " + 
    y.getCenturies() + "c + " + y.getDecades() + "d" 
); 
相关问题