【问题标题】:Not getting the value x and y i.e (10 and 5) in the replace method?在替换方法中没有得到值 x 和 y 即(10 和 5)?
【发布时间】:2017-03-27 10:19:03
【问题描述】:
package interview_programs;
public class Swapping {

    int x,y ;

    Swapping(int a, int b){ 
    int x = a;      
    int y = b;
    System.out.println("the valueof x is" + x);
    System.out.println("the valueof y is" + y);     
    }

    public void replace(){
    x = x + y;
    y = x - y;
    x = x - y;          
    System.out.println("the value after swap");
    System.out.println("the valueof x is" + x);
    System.out.println("the valueof y is" + y);             
    }   

    public static void main (String args[]) {   
    Swapping Swap = new Swapping(10,5);
    Swap.replace(); 
    }
}

这是控制台的输出。

输出:

x的值为10

y的值为5

交换后的值

x的值为0

y的值为0

【问题讨论】:

    标签: java class methods constructor scope


    【解决方案1】:

    您没有初始化您的类级 x 和 y,而是在您的构造函数中初始化本地 x 和 y。

    将“int x = a”替换为“x = a”,将“int y = b”替换为“y = b”。

    【讨论】:

      【解决方案2】:

      从 x 和 y 中取出 int。这些是创建局部变量而不是设置局部类字段。

      Swapping(int a, int b){ 
        x = a;      
        y = b;
        System.out.println("the valueof x is" + x);
        System.out.println("the valueof y is" + y);     
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-18
        • 2019-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多