在java上使用类中的类

时间:2018-04-04 07:54:20

标签: java class

import java.util.*;

public class Lab21_Vars {

    public static void main(String[] args) {

        int i = 0;
        int j = 0;
        int var0, var1;

        // Fix 1: Correctly typecast 5.0 to an int so it can assigned to var3.
        int var2 = 0, var3 = (int) 5.0;

        // Fix 2: Correctly declare a variable as an array.
        int[] arri0 = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

        double[] arrd0 = {0.0, 1.0, 2.0, 3.0, 4.0};

        // Fix 3: What's wrong with temp? Fix it.
        int temp = 0;
        if (i < j) {
            System.out.println("Temp is " + temp);
        } 
        else {
            System.out.println("Temp is " + temp);
        }

        // Fix 4: Correctly calculate square of sums and print it as total.
        int total = 0;

        for (i = 0; i < 10; i++) {
            total += i*i;
        }
        System.out.println("i value is " + i);
        System.out.println("Total is " + total);

        // Fix 5: Figure out the logical error in lines 36-42, and correct it.
        Cheese jack;
        Cheese monterey = new Cheese("Monterey");
        jack = monterey;
        System.out.println("Monterey name is " + monterey.getName());
        jack.setName("Jack");
        System.out.println("Jack name is " + jack.getName());
        System.out.println("Monterey name is still " + monterey.getName());

        // Fix 6: Make the following code shorter by combining redundant 
        //        (unnecessary/duplicate) statements
        Scanner input = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int num1 = input.nextInt();

        {
            System.out.print("Enter second number: ");
            int num2 = input.nextInt();

            if (num1 > var3 )
                System.out.println("First is greater");
            else
                System.out.println("First is Less than or equal");


            if (num2 < var3)
                System.out.println("Second is Less");   
            else
                System.out.println("Second is greater than or equal to");

            System.out.println("The first number was " + num1);

        }

    }
}

我的大多数代码都在运行,但奶酪部分却没有。我知道我需要创建另一个类,以便代码可以工作。我是否需要创建具有不同功能的不同构造函数?我自己尝试创建奶酪课,但我没有走上正确的道路。据我所知,该类将在不同的java项目中,但正如我所提到的,我无法让它工作。非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

//修复5 当你分配时 jack = monterey;

您只是在内存中引用相同的对象,因此在打印时

jack.getName() and monterey.getName()

两者都会给出与指向单个对象相同的值。 而不是直接在cheese类中使用make new函数来使用new关键字克隆对象。