调用主类

时间:2017-11-01 06:19:48

标签: java

这里我试图运行两个数字的附加程序。 我创建了三个类student1student2example。我正在两个类中接受用户输入并想要添加它们,但不幸的是它显示错误。

import java.util.Scanner;
class student1
{
    public int sum()
    {
        int a;
        Scanner kb=new Scanner(System.in);
        System.out.println("Enter a number");
        a=kb.nextInt();
        return(a);

    }
}
class student2
{
    public int sum2()
    {
        int b;
        Scanner kb1=new Scanner(System.in);
        System.out.println("Enter second number");
        b=kb1.nextInt();
        return(b);

    }
}
public class example
{
    public static void main(String[] args)
    {
        student1 o1=new student();
        o1.sum();
        student2 o2=new student2();
        o2.sum2();
        int c=a+b;
        System.out.println("Sum of " +a+ " and " +b+  " is " +c);
    }
}

我希望此代码执行ab的附加功能,同时将值存储到c并显示结果。 错误:显示错误无法找到符号

1 个答案:

答案 0 :(得分:3)

将您的代码更改为

    student1 o1=new student();
    int a = o1.sum();
    student2 o2=new student2();
    int b = o2.sum2();
    int c=a+b;
    System.out.println("Sum of " +a+ " and " +b+  " is " +c);

因为你不能神奇地使用用其他方法定义的变量