简体   繁体   English

如何在另一个类中使用静态类中的变量?

[英]How do I use a variable from a static class in another class?

I's trying to build an encoder like the "Enigma Machine" and I have this code so far where I'm trying to get comboOne() to use the "s" variable from main(): 我正在尝试构建一个像“ Enigma Machine”之类的编码器,到目前为止,我已经在这段代码中尝试让comboOne()使用main()中的“ s”变量:

import java.io.*;

public class main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What would you like to encode?");
        String s = br.readLine();

        s.toCharArray();
        System.out.println(s);

        //comboOne comboOne = new comboOne();
    }
}

Just to encode one letter I've written this: 只是为了编码一个字母,我写了这个:

public class comboOne extends main
{
    main m = new main();
    char message = s.toCharArray();
        if(message == 'a')
    {
        System.out.println('b');
    }
}

I am quite new so apologies if I am making an obvious mistake but I think this would be a fun challenge for myself. 如果我犯了一个明显的错误,我很抱歉,但是我认为这对我自己是一个有趣的挑战。 Please send help and thanks for helping :) 请发送帮助,感谢您的帮助:)

Add outside your Main.main method 在您的Main.main方法之外添加

public static String s;

Then use Main.s to access the String in a static way. 然后使用Main.s以静态方式访问String。 Since it is static it does not need to be instantiated an can directly be called from the class. 由于它是静态的,因此不需要实例化,可以直接从类中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用一个类中的静态变量来更新另一个类中的非静态实例变量? - How to use a static variable from a class to update a non-static instance variable in another class? 如何从一个方法,另一个类的变量数据中读取公共静态变量并获取更新的数据 - How do I read in a public static, with variable data from a method, from another class and get updated data 如何通过从主类获取变量以将其用作标题来影响另一个类的JFrame? - How do I affect a JFrame from another class by getting the variable from the main class to use it as the title? 如何从公共static void main到另一个类调用变量? - How do I call a variable from the public static void main to another class? 如何从另一个类访问静态变量? - How to access static variable from another class? 如何使用另一个类中的对象的特定变量? - How do I use a specific variable of an object that is in another class? 如何使用来自另一个类的Action Listener的目录路径变量? - How do I use a directory path variable from an Action Listener from one class in another? 如何从另一个类的静态方法更改静态变量的值 - how to change the value of a static variable from a static method of another class 如何使用Java中另一个类的变量 - How can I use a variable from another class in Java 如何从另一个类访问一个变量? - How Do I Access One Variable From Another Class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM