我在编程(java)课程的介绍中有这个项目。它应该使用方法创建一个字符串乐器,并播放乐器等。我已经在C#中完成了这个项目,但出于某种原因我似乎无法在java中使用它。我一直收到一个错误,"非静态变量不能从静态内容中引用。我在这里搜索过,到目前为止还没有解决方案适合我。请帮忙。谢谢!!
`/ * *要更改此许可证标题,请在“项目属性”中选择“许可证标题”。 *要更改此模板文件,请选择“工具”|模板 *并在编辑器中打开模板。 * /
package egreenhornfinal;
import java.util.Scanner;
/**
*
* @author Eddie
*/
public class EGreenhornFinal {
class Guitar
{
boolean isTuned; //Guitar starts off not tuned
boolean isPlaying; //Guitar is not playing at start
boolean isBroken; //Guitar has broken a string
boolean isFixed; //Broken String has been fixed
boolean isNotPlaying; //Guitar has stopped playing
boolean songOver; //The song is over now.
//array for Guitar strings
char[] GuitarStrings = { 'e', 'A', 'D', 'G', 'B', 'E' };
private int numberofStrings = 6;
//default Guitar object
public Guitar()
{
isTuned = false;
isPlaying = false;
isBroken = false;
isFixed = false;
isNotPlaying = false;
songOver = false;
System.out.println("The Guitar is not playing, and it is not tuned. All Strings are intact.\n");
}
public Guitar(boolean T, boolean P)
{
isTuned = T;
isPlaying = P;
}
public boolean playGuitar()
{
System.out.println("The Guitar is playing!\n");
return isPlaying = true;
}
public boolean stopPlaying()
{
System.out.println("The Guitar has stopped playing.\n");
return isNotPlaying = true;
}
public boolean tuneGuitar()
{
System.out.println("The Guitar is being tuned!\n");
return isTuned = true;
}
public boolean brokenString()
{
System.out.println("One of the strings was too tight, it has broken!\n");
return isBroken = true;
}
public boolean fixedString()
{
System.out.println("The broken string has been fixed, the guitar is now playing again.\n");
return isFixed = true;
}
public boolean EndOfSong()
{
System.out.println("The Guitar has stopped playing because the song is over.\n");
return songOver = true;
}
}
/**
*
* @param args
*/
public static void main(String[] args)
{
String WantToPlay = "Y";
do
{
Guitar MyGuitar = new Guitar();
//Error-- Non static variable being referenced from static content??
boolean varIsTuned = false;
varIsTuned = MyGuitar.tuneGuitar();
boolean varIsPlaying = false;
varIsPlaying = MyGuitar.playGuitar();
boolean varIsNotPlaying = true;
varIsNotPlaying = MyGuitar.stopPlaying();
boolean varIsBroken = false;
varIsBroken = MyGuitar.brokenString();
boolean varIsFixed = false;
varIsFixed = MyGuitar.fixedString();
boolean varsongOver = false;
varsongOver = MyGuitar.EndOfSong();
System.out.println("Would you like to play the Guitar again? (enter Y for yes, and N for no)");
Scanner inUsr = new Scanner(System.in);
WantToPlay = inUsr.nextLine();
}
while (WantToPlay == "Y");
}
}
`
答案 0 :(得分:1)
您必须将内部类声明为静态。否则它是非静态的(您可以从非静态内部类访问外部this-pointer)。