有 Java 编程相关的问题?

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

java函数解密程序

我对Java和编程都很在行这就是我学习它的原因:)我需要你的帮助来做一个练习。我需要在arg上做一些修改来创建函数破译器

import java.util.StringBuffer;

public class Decipherer{

    String arg ="aopi?sedohtém@#?sedhtmg+p9l!";

    int nbrChar = arg.length()/2;

    String arg2 = arg.substring(5, nbrChar-1);

    String arg3 = arg2.replace("@#?", " ");

    String arg4 = new StringBuilder(arg3).reverse().toString();

    return arg4;

}

public static void main(String[] args) {

    Decipherer mesage1 = new Decipherer("0@sn9sirppa@#?ia'jgtvryko1");
    Decipherer message3 = new Decipherer("q8e?wsellecif@#?sel@#?setuotpazdsy0*b9+mw@x1vj");
    Decipherer message4 = new Decipherer("aopi?sedohtém@#?sedhtmg+p9l!");

}

--

Exception in thread "main" java.lang.Error: Unresolved compilation problems: The constructor Decipherer(String) is undefined The constructor Decipherer(String) is undefined The constructor Decipherer(String) is undefined Syntax error, insert "}" to complete ClassBody

    at Decipherer.main(Decipherer.java:24)

我不明白为什么它会问另一个“}”。谁能给我解释一下吗


共 (1) 个答案

  1. # 1 楼答案

    main方法必须在类中。你可以把它放在Decipherer。此外,您正在执行的操作必须放在一个方法中,以便能够返回某些内容。你需要一个接受String的构造函数,例如

    public class Decipherer {
    
      private final String input;
    
      // constructor accepting String
      public Decipherer(String input) {
        this.input = input;
      }
    
      public String decipher() {
    
        int nbrChar = input.length() / 2;
    
        String arg2 = input.substring(5, nbrChar - 1);
    
        String arg3 = arg2.replace("@#?", " ");
    
        return new StringBuilder(arg3).reverse().toString();
      }
    
      // main method inside class
      public static void main(String[] args) {
        Decipherer decipherer1 = new Decipherer("0@sn9sirppa@#?ia'jgtvryko1");
        String message1 = decipherer1.decipher();
        Decipherer decipherer2 = new Decipherer("q8e?wsellecif@#?sel@#?setuotpazdsy0*b9+mw@x1vj");
        Decipherer decipherer3 = new Decipherer("aopi?sedohtém@#?sedhtmg+p9l!");
      }
    }
    

    通过执行new Decipherer("0@sn9sirppa@#?ia'jgtvryko1");,类型为Decipherer的对象将使用字段input创建。然后,您可以在这个对象上调用方法decipher()

    或者,您也可以不使用构造函数,公开一个静态方法来解密,例如

    public static String decipher(String input) {
        int nbrChar = input.length() / 2;
        String arg2 = input.substring(5, nbrChar - 1);
        String arg3 = arg2.replace("@#?", " ");
        return new StringBuilder(arg3).reverse().toString();
      }
    

    您可以在主方法中调用它作为final String message = Decipherer.decipher("0@sn9sirppa@#?ia'jgtvryko1");