【问题标题】:Trouble solving generated output解决生成的输出问题
【发布时间】:2017-12-07 19:27:00
【问题描述】:

我对 Java 还很陌生,在准备考试时遇到了麻烦。此示例问题要求展示工作以提供此代码生成的确切输出:

public class Lab7Experiment extends JApplet
{
    int x=3, y=-3, z=5;
    int someValues [] = {2, -6, 4, -4, 6, -2};

    public void init()
    {
        char y = 'y';
        z=10;
        System.out.println("Print 1 x,y,z, = "+x+" "+y+" "+z);
        y= sub1(x,y,z);
        System.out.println("Print 2 x,y,z, = "+x+" "+y+" "+z);
        x= sub2(x, someValues);
        System.out.println("Print 3 x,y,z, = "+x+" "+y+" "+z);
        for (int i=0; i<3; i++)
            System.out.println("Print "+(i+4)+" "+someValues[i*2]+" "+someValues[i*2+1]);
    }
    public char sub1(int a, char b, int c)
    {
        if (a>=c)
            return b;
        else
        {
            c=15;
            z=25;
            return 'z';
        }
    }
    public int sub2(int x, int [] anArray)
    {
        int y=0;
        for(int i=anArray.length-1; i>=0; i--)
        {
            if (anArray[i] > x)
            {
                anArray[i]=x;
                y++;
            }

        }
        x=100;
        return y;
    }

}  

我无法理解在生成此输出时如何使用 someValues 数组和 anArray。我已经在 Eclipse 中运行它,所以我可以检查我的答案,但我不确定为什么生成的输出结果是这样的。谁可以给我解释一下这个?会非常感激。谢谢

【问题讨论】:

  • 您能说得更具体些吗?运行代码时您会看到哪些值,而您希望看到哪些值?
  • @markspace 是的!当我运行它时,我看到: Print 1 x,y,z, = 3 y 10 Print 2 x,y,z, = 3 z 25 Print 3 x,y,z, = 2 z 25 Print 4 2 -6 Print 5 3 -4 打印 6 3 -2。由于 System.out.println() 中没有写“打印 4、5 等”; ,这些是从哪里来的?而对于打印 2 和 3,为什么现在用“z”代替“y”?解决这个问题时我什至不知道从哪里开始(我们必须手动解决)。

标签: java arrays return output equation-solving


【解决方案1】:

这是一个很长的答案,不是要解决的问题......

顺便说一句:

  1. 打印 1 x,y,z, = 3 y 10

因为类变量x = 3: int x=3 然后使用局部变量 char y = 'y' 并将 z 更改为 10 z=10;

  1. 打印 2 x,y,z, = 3 z 25 因为类变量x 仍然保持不变。在sub1:3 不是>= 10(通过z),所以else 分支:

        `c=15;` does not change passed `x` Java is `pass-by-value`
        `z=25;` changes class variable `z` to 25
        return 'z';
    

    那么局部变量 y 现在是 'z'

  2. 在 sub2 之后你有:

    class variable x = 2
    class variable y =-3
    class variable z = 25
    local variable y = 'y'
    更新:class variable someValues [] = {2, -6, 3, -4, 3, -2};

然后按照最后一个循环从someValues 获取 Print 4,5 和 6 作为:

`Print 4 2 -6`
`Print 5 3 -4`
`Print 6 3 -2`

祝你好运!

【讨论】:

  • 谢谢!我想我开始明白了。不过,我不明白的一件事……对于打印 5,第二个值 3 怎么样?因为 someValues[2] 会拉出 4 的值?
  • 对不起 - 我的错 - 复制粘贴错误。现在查看更新的someValues。实际上 sub2 用 x (3) 替换所有大于 x 的值,并返回有多少被替换为 2,然后 x 变为那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2021-05-06
  • 2020-04-18
相关资源
最近更新 更多