1

此代码应该在输入对话框中接收全名字符串示例“Billy Bob Smith”,并在消息对话框中将首字母作为字母组合示例“BBS”​​输出。但由于某种原因,主要方法不会让我访问 fullName 变量。

import javax.swing.*;

public class HardMonogram {
     //---------- ATTRIBUTES ----------//
     private String fullName;
     private String monogram;
     private String first;
     private String middle;
     private String last;


     //---------- METHODS ----------//
     public String getInitial(String seperateName) {
           return seperateName.substring(0, 1);
     }

     public void getSeperateName(String fullName) {
           first  = fullName.substring(0, fullName.indexOf(" "));
           middle = fullName.substring(fullName.indexOf(" ") + 1, fullName.length());
           last   = middle.substring(middle.indexOf(" ") + 1, middle.length());
           middle = middle.substring(0, middle.indexOf(" "));
     }

    public void setMonogram() {
          monogram = getInitial(first)  +
                     getInitial(middle) +
                     getInitial(last);

    JOptionPane.showMessageDialog(null, monogram);
    }

    public static void main(String[] args) {
           myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");

           HardMonogram myMono = new HardMonogram();
           myMono.getSeperateName(myMono.fullName);
           myMono.setMonogram();

    }


}

给了我这个构建错误

/Users/aaron/School/Fall 2012/CSCI-C 201/Labs/LB08/HardMonogram.java:33: error: cannot find symbol
    myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
    ^
symbol:   variable myMono
location: class HardMonogram
1 error
[Finished in 1.2s with exit code 1]

这是我对 java 类的介绍,但我不知道为什么我不能访问该变量。我显然忽略了一些东西。有任何想法吗?

4

3 回答 3

5

更新:

再次阅读问题后,您只需要在创建实例后移动 main 方法中的第一行。

       HardMonogram myMono = new HardMonogram();
       myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
       myMono.getSeperateName(myMono.fullName);
       myMono.setMonogram();
于 2012-11-29T21:12:41.937 回答
4

简单地放在myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");对象声明(HardMonogram myMono = new HardMonogram();)之后。

于 2012-11-29T21:16:47.417 回答
0

MyMono 尚未在您的 main 方法的第一行中声明。将其添加到开头。

public static void main(String[] args) {
      HardMonogram myMono = new HardMonogram();
      myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
      myMono.getSeperateName(myMono.fullName);
      myMono.setMonogram();

}
于 2012-11-29T21:18:38.023 回答