gpt4 book ai didi

java - 不明白简单java程序的输出

转载 作者:行者123 更新时间:2023-12-02 00:06:17 25 4
gpt4 key购买 nike

public class Test10 
{
public static void main( String[] args )
{
Thing2 first = new Thing2( 1 );
Thing2 second = new Thing2( 2 );
Thing2 temp = second;
second = first;
first = temp;
System.out.println( first.toString() );
System.out.println( second.toString() );
Thing2 third = new Thing2( 3 );
Thing2 fourth = new Thing2( 4 );
third.swap1( fourth );
System.out.println( third.toString() );
System.out.println( fourth.toString() );
second.setCount( fourth.getCount() );
third = first;
System.out.println( third == first );
System.out.println( fourth == second );
System.out.println( first.toString().equals( third.toString() ) );
System.out.println( second.toString().equals( fourth.toString() ) );
System.out.println( first.toString() );
System.out.println( second.toString() );
System.out.println( third.toString() );
System.out.println( fourth.toString() );
first = new Thing2( 1 );
second = new Thing2( 2 );
first.swap2( second );
System.out.println( first.toString() );
System.out.println( second.toString() );
}
}



class Thing2
{
private int count;

public Thing2( int count )
{
this.count = count;
}
public int getCount()
{
return this.count;
}
public void setCount( int count )
{
this.count = count;
}
public String toString()
{
String s = " ";
switch( this.count )
{
case 1:
s = s + "first ";
case 2:
s = s + "mid ";
break;
case 3:
s = s + "last ";
break;
default:
s = s + "rest ";
break;
}
return s;
}
public void swap1( Thing2 t2 )
{
int temp;
temp = this.getCount();
this.setCount( t2.getCount() );
t2.setCount( temp );
}
public void swap2( Thing2 t2 )
{
Thing2 temp;
Thing2 t1 = this;
temp = t1;
t1 = t2;
t2 = temp;
}
}

Given the following definition of class Thing2, what is the output of the Java application Test10?

嘿伙计们,这是我的一门课。有两个类(上面列出):Thing2 和 Test10。这是输出,但我不明白如何获得输出(即什么指向什么以及所有内容得到解决的顺序是什么?)。谢谢!

mid
first mid
rest
last
true
false
true
true
mid
last
mid
last
first mid
mid

最佳答案

一个技巧是 switch 语句中的 case 1 没有 break 语句,因此代码继续执行 case 2 指令并创建字符串“first mid “而不是 Thing(1) 的“第一个”

像这样向打印语句添加注释可能会有所帮助

System.out.println("First is " + first.toString());
System.out.println("third == first?" + (first == third));

如果您这样做,请添加更多打印语句。

将每个变量视为一个大箭头。

语句a = new Thing(2)创建一个带有单词“mid”的Thing,并将a箭头指向它。

语句a = b采用b箭头所看到的任何内容,并将a箭头指向同一事物。

关于java - 不明白简单java程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com