[英]Methods & Variables Calling Questions
我之前写过这段简短的代码:
public class Check {
public static int gold, silver;
public int level=1;
public static void main(String[] args) {
System.out.println("You are now level " + level + "!");
String num1 = JOptionPane.showInputDialog("Enter a positive number:");
int num2 = Integer.parseInt(num1);
if (num2 < 0) {
next();
} else {
main();
}
}
public void next() {
System.out.println("Thank you!");
}
}
这段代码有3个问题:
如果我创建一个公共静态Integer变量,则在声明它时不能为其设置数字。 我必须在声明时设置一个数字。 编辑:我不好,声明时可以给它分配一个数字。
如果我创建一个公共Integer变量,则可以对其进行声明并为其设置一个数字,但是由于某些原因,我不能在公共静态void Main中使用它,我也必须这样做。
由于next()不是静态void,所以无法从main(String [] args)void调用它。 我不想将next()设为静态,因为那样我将无法使用非静态的公共Integer。
我无法从main()本身返回(调用)main()。 当检测到无效输入时,这是必要的。
这些问题我该怎么办?
如果不想使用静态方法,则必须在main方法中创建一个类对象,然后使用它来调用next()方法。
Check obj = new Check();
obj.next();
如果我创建一个公共静态Integer变量,则在声明它时不能为其设置数字。
是的你可以。
如果我创建一个公共Integer变量,则可以对其进行声明并为其设置一个数字,但是由于某些原因,我不能在公共static void Main中使用它。
那是因为静态方法不能利用非静态属性。
我无法从main()本身返回(调用)main()。 当检测到无效输入时,这是必要的。
是的,可以,但是您需要传递参数。
尝试以下变体:
public class Check {
public static int gold, silver;
public static int level = 1;
public static void main( String[] args ) {
System.out.println( "You are now level " + level + "!" );
String num1 = JOptionPane.showInputDialog( "Enter a positive number:" );
int num2 = Integer.parseInt( num1 );
if( num2 < 0 ) {
next();
}
else {
main(args);
}
}
public static void next( ) {
System.out.println( "Thank you!" );
}
}
几条评论。
1) 如果我创建一个公共静态Integer变量,则在声明它时不能为其设置数字
为什么?
您应该很容易就能这样声明它:
public static int level = 1;
然后,您的代码将可以正常工作。
2)避免静态 -不要从main
调用程序逻辑,请使用main
引导应用程序:
public int gold, silver;
public int level = 1;
public static void main(String[] args) {
new Check().read();
}
public void read() {
System.out.println("You are now level " + level + "!");
String num1 = JOptionPane.showInputDialog("Enter a positive number:");
int num2 = Integer.parseInt(num1);
if (num2 < 0) {
next();
} else {
read();
}
}
public void next() {
System.out.println("Thank you!");
}
因此,您要使所有实例都成为作用域,然后在main
创建一个Check
实例 。
我还要指出的是,您使用的EDT是Swing GUI类,它破坏了Swing的单线程模型,因此此代码从根本上来说是有缺陷的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.