【问题标题】:How do I replace a part of a variable with another variable如何用另一个变量替换变量的一部分
【发布时间】:2018-09-22 23:23:16
【问题描述】:

我试图在这里不使用大量的 IF 语句。 我有 26 个不同的盒子,分别命名为 txtA、txtB、txtC 等。

我要创建的是一种可以使用变量“box”的方法来给出

String result = txt(box).getText(); 

方框将替换任何字母。

谢谢,这是我的代码

public static String getTextBoxInput(char box) {        
    String result = txtA.getText();
    return result;
}

【问题讨论】:

  • 你想要一个数组。
  • ArrayList<JTextField> 或 Map,例如 HashMap。

标签: java variables


【解决方案1】:

构建一个包含您的文本框的Map<String, TextBox>(),以您的字母为键并以这种方式使用它:

public static String getTextBoxInput(char box) {
    TextBox textBox = textBoxMap.get(box);

    if (textBox != null)    {
        return textBoxMap.get(box).getText();
    }

    return null;
}

你的地图是:

"A", txtA
"B", txtB

等等。这是您最简单的选择,既可以添加另一个框,也可以快速找到它们。

【讨论】:

    【解决方案2】:

    这里可以使用数组。我希望这会有所帮助。

    import java.util.*;
    
    public class Task {
        static BOX Box[] = new BOX[26];
        static Scanner in = new Scanner(System.in);
    
    
        /*assuming that the variable box can only get input as an English uppercase
          alphabet and characters stored in box can range from A to Z.
        */
        public static String getTextBoxInput(char box) {
            String result = Box[box - 65].getText(); //ASCII value of 'A' is 65
            return result;
        }
    
    
        public static void main(String[] args) {
            //initializing the elements of BOX with their respective Strings
            for(int i = 0; i < 26 ; i++)
                Box[i] = new BOX( "Sample_String "+(i+1) );
    
            char box = in.next().charAt(0);
            String result = getTextBoxInput(box);
    
            System.out.print("RESULT : "+result);
        }
    }
    
    class BOX {
        String text;
        public BOX(String text) {
            this.text = text;
        }
    
        public String getText() {
            return text;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2022-11-17
      • 2020-03-25
      • 2018-01-24
      相关资源
      最近更新 更多