0
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; 
  } 
} 

给定以下类 Thing2 的定义,Java 应用程序 Test10 的输出是什么?

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

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

2 回答 2

2

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

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

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

一个你这样做,添加更多的打印语句。

把每个变量想象成一个大箭头。

该语句a = new Thing(2)用“mid”一词创建了一个事物,并将a箭头指向它。

该语句a = b采用b箭头所看的任何东西并将箭头指向a同一事物。

于 2012-12-11T02:31:48.123 回答
1

3条建议:

  1. switch 中的 case 1 不包含中断。因此,当满足案例 1 时,控制将流向案例 2,甚至会执行案例 2。

  2. 使用一些打印语句,以便您知道您在控制台上打印的内容。

  3. 你的问题不准确。你有代码。你有输出。你是说你不明白如何得到输出。可能您需要通读代码并了解控制在 Java 程序中的流动方式。如果您正在寻找一些特定的控制流结构,那么我们可以提供帮助。根据您所说的,我们不知道您面临什么问题。尽管如此,我还是会建议你“分而治之”的策略。注释掉所有内容并执行小的逻辑代码片段,当您理解了第一小部分时,取消注释几行,运行并查看输出,然后您可能可以将执行的内容和打印的内容联系起来。示例:首先处理一个交换函数。

于 2012-12-11T03:21:04.117 回答