java - 如何在另一种方法中使用来自一种方法的用户输入字符串?

标签 java string methods

此程序的这一点是将用户名的字符长度限制为 20 个字符。它是目前仅包含 Main 方法的较大程序的一部分。为了清理和阐明我的代码,我想将各种功能分成不同的方法。

目前,我正在尝试设置类变量,以便它们可以在多种方法中使用。这是我目前所拥有的:


public class Program
{
    Scanner read = new Scanner(System.in);
    String firstName = read.nextLine();
    String lastName = read.nextLine();
    
    public void main(String[] args) {
        domainCharLimit();
    }
    
    public void domainCharLimit() {
        String firstNameNew = firstName.replace("'", "");
        String lastNameNew = lastName.replace("'", "");
        String domainUsername = firstNameNew + "." + lastNameNew;
        if (domainUsername.length()>20) {
                String cutName = domainUsername.substring(0, 20);
                domainUsername = cutName;
            }
        System.out.print(domainUsername);
    }    
}

我已尝试将一个或两个方法设置为静态,但未能解决问题。在这种状态下,程序运行时不会返回错误,而是“无输出”

最佳答案

Main 方法必须是静态的!它是您程序的入口,它的签名必须是这样的。

为了在其中调用非静态方法,您需要实例化一个对象并在该对象上调用它。在你的情况下是这样的

public static void main(String[] args) {
   Program p =  new Program();
   p.domainCharLimit();
}

关于java - 如何在另一种方法中使用来自一种方法的用户输入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70238312/

相关文章:

java - 如何在 Findbugs 中使用 Checker Framework 注释?

javascript - codePointAt 和 charCodeAt 的区别

swift - 从字符串中删除前六个字符(Swift)

swift - 是否存在确定类型应该用字符串初始化的协议(protocol)?

ruby - 更改方法中传递的变量

java - 为什么我的 String 方法允许返回 String 和 int 值?

Java,小程序 : How to block the activation of paint() before init() finishes it's work

java - 使用JDK 1.7编译Android项目

java - 使用 facebook API 的 Stream.publish 方法时获取权限错误

java - org.apache.bcel.classfile.ClassFormatException : Invalid byte tag in constant pool: 19