此代码应在输入对话框中接收全名字符串示例“Billy Bob Smith”,并在消息对话框中将首字母输出为字母组合示例“BBS”。但由于某种原因,main方法不允许我访问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类介绍,但我不知道为什么我无法访问变量。我显然忽略了一些东西。任何想法?
答案 0 :(得分:5)
更新
在再次阅读问题后,您只需要在创建实例后在main方法中移动第一行。
HardMonogram myMono = new HardMonogram();
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
答案 1 :(得分:4)
只需在对象声明(myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
)之后放置HardMonogram myMono = new HardMonogram();
。
答案 2 :(得分: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();
}