gpt4 book ai didi

java - 方法中输入每个参数后如何打印?

转载 作者:行者123 更新时间:2023-12-02 02:47:09 24 4
gpt4 key购买 nike

我知道我的问题,但我似乎无法找到解决方法。

我想做的是在用户给出他们喜欢的用户名后,我想在输入旁边打印电话号码,而我遇到的问题是这样的。

我会让用户输入,

用户名:电话号码:然后现在可以输入

相反,我想要的是这样的:

用户名:从方法参数中输入......

电话号码:与上面相同

更新版本:

这是我得到的错误

userName cannot be resolved to a variable

 public void createCustomer(String userName) {

System.out.print("Enter username: ");
this.user = input.nextLine();
this.user = userName;

this.password = password;
this.address = address;
this.phoneNum = phoneNum;
this.email = email;
}

public static void main (String args[]) {
CustomerUI customer = new CustomerUI();
Scanner input = new Scanner(System.in);

if(shouldCreate() == true) {
customer.createCustomer(userName);
}
}

最佳答案

输出提示后可以扫描每一行输入用户名或电话号码。例如:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter username: ");
String username = scanner.nextLine();
System.out.println("Username: " + username);

电话号码也是如此。然后,您可以将值传递给 createCustomer 方法:

customer.createCustomer(username, phoneNumber, otherVar, anotherVar, lastVar);

编辑以解决更新的代码:您没有在主方法中定义用户名。如果我们检查您的代码,则会发生以下情况:

  • 我们进入定义客户(CustomerUI 对象)和输入(Scanner 对象)的主方法。
  • 如果 shouldCreate() 方法返回 true,我们将使用 customer.createCustomer(userName) 创建客户。然而,此时,用户名尚未在任何地方定义(例如String userName;)
  • 在 createCustomer 中,我们将行 “输入用户名:” 打印到控制台
  • 然后,我们使用 input.nextLine()user 类变量设置为在控制台中输入的行。然而,此时,我们还没有在此方法中定义名为 input 的变量。它在 main 中定义,但作为局部变量。因此,无法通过其他方法访问它。
  • 然后从 userName 方法参数分配 user 类变量。这将覆盖 input.nextLine() 值,使该行无用

我会推荐什么:

  • Scanner input = new Scanner(System.in) 行放入 createCustomer 方法
  • 删除 createCustomer 方法的参数,而是每次从 input.nextLine() 方法分配值

或者:

  • 保留主方法中的 Scanner input = new Scanner(System.in)
  • input.nextLine() 方法调用移至 main 方法中,并将其值分配给局部变量
  • 将这些变量传递给 createCustomer 方法,然后该方法可以将其分配给类变量

关于java - 方法中输入每个参数后如何打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416066/

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