有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java from方法中我的变量返回的简单问题

java新手。我有一个简单的问题。我在实验室工作,不明白为什么我的代码返回一个空白变量。因此,调用该方法并输入名称,它应该返回名称,然后将其发送到下一个方法进行打印。相反,它会打印“你好!”。有什么想法吗?`//

This application gets a user's name and displays a greeting
import java.util.Scanner;
public class DebugThree3
{
   public static void main(String args[])
   {
      String name = " ";
      getName(name);
      displayGreeting(name);           
   }
   public static String getName(String name)
   {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter name ");
      name = input.next();
      return name;
   }
   public static void displayGreeting(String name)
   {
      System.out.println("Hello, " + name + "!");
   }
}`

共 (1) 个答案

  1. # 1 楼答案

    Java是按值传递的。让我们从简单的ints开始:

    int x = 5;
    changeIt(x);
    System.out.println(x); // this prints.. 5. always.
    
    public void changeIt(int x) {
        // x is local to this method. It is created when this method begins..
        x = 10;
        // and now x just goes away. I set to '10' a thing that disappears here..
        // Therefore this method does nothing useful whatsoever!
        // in the caller context? x is.. still 5. I modify my own copy, not yours.
    }
    

    PBV意味着代码传递给changeIt方法的是值5不是“x”或“x”的位置,也不是以任何其他方式表示“x,变量”

    现在,对于所有非原语(只有int、float、double、long、boolean、char、short和byte是原语。所有其他类型都是非原语),“value”是引用。参考资料是指向宝藏的藏宝图。字符串是非基元的,因此:

    String x = "Hello";
    // x is a treasure map.
    //If you follow the map, it leads to the treasure 'Hello'.
    
    x.toLowerCase(); // the dot operator is: "Follow the treasure map"
    x = "Goodbye"; // this makes a new treasure map..
    // x is a treasure map; it has been wiped out and overwritten with a map to "Goodbye".
    
    changeIt(x); // this makes a copy of the _TREASURE MAP_. Not the treasure.
    

    现在,如果我有一张藏宝图,我复制一份,然后把藏宝图递给你,你用你的地图副本把它撕成碎片,我的地图不会改变

    然而,如果你按照你的藏宝图找到宝藏并清空盒子,然后我按照我的地图,我会找到。。。所有的宝藏都被拿走了

    现在,绳子是一种不可改变的财富。这就是所谓的“不可变”。您可以按如下方式识别它们:它们上的任何方法都不会更改它。例如,someString.toLowerCase()生成一个新字符串;它不会修改它。没有方法可以修改它

    因此,在这里也没有办法做你想做的事情。要改变现状,您需要制作一个新的宝藏并返回一个新的宝藏地图。这确实有效:

    String x = "Hello";
    x = changeIt(x); // update my map!
    
    public String changeIt(String x) {
        return x.toLowerCase(); // make a new treasure, then a new map, and return that.
    }
    

    然而,如果你有一个可变的对象,传递一个藏宝图的副本会导致改变。例如:

    List<String> list = new ArrayList<String>();
    list.add("Hello");
    System.out.println(list); // prints [Hello]
    changeIt(list);
    System.out.println(list); // prints [Hello, World]
    
    void changeIt(List<String> list) {
        //list is a copy of the treasure map.
        list.add("World");
        // but '.' is the: Follow the treasure map operator.
        // I went to the treasure and put a new item in the box.
        // THAT is visible to the caller!
    
        list = null; // but this is not; I am wiping out MY copy of the map.
    }