2017-02-24 49 views
-1

所以,对于一个任务,我必须这样做的一部分,但如果部分是红色的,我不明白为什么所以,我认为这是基本的,但我需要知道

if (int >=1 && int<=7){ 
    Scanner sc = new Scanner(System.in); 
    String direction; 
    System.out.println("Enter your choice: "); 
    direction=sc.nextD(); 
    if (direction = 'left'){ 
     maze.push('left'); 
     System.out.println("Pushed left to stack"); 

我意识到我忘了它的一部分。 更新的代码:

Stack maze = new Stack(); 
for(int x=1; x<=10; x++) 
{ 
    Random ran = new Random(); 
    int a = ran.nextInt(10) + 1; 
    if (int a>=1 && int a<=7){ 
     Scanner sc = new Scanner(System.in); 
     String direction; 
     System.out.println("Enter your choice: "); 
     direction=sc.nextLine(); 
     if (direction.equals ("left") || direction.equals ("Left")){ 
      maze.push("left"); 

的if(INT A> = 1 & & INT一个< = 7)部分不工作。一切是好的

+0

这是编译器告诉你的东西是你的代码错误。我不是编译器,但是离开我的头顶部''left''不是'String',在Java中,字符串用双引号表示:'“left”'。 – azurefrog

+2

另外,'if(direction =“left”)'是赋值,而不是比较。另外,'if(direction ==“left”)'比较引用相等,并且也会失败。请参阅[如何比较Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – azurefrog

+0

替换'if(int a> = 1 && int a <= 7){'with'if(a> = 1 && a <= 7){''int a'将尝试声明一个名为a的新整数。 – alexgbelov

回答

1

因此,这里有一些问题,我看到:

  1. int不是一个变量;它是一个原始类型的名称。您不能在java中将任何变量命名为int,并且您当然不能与其进行比较。

  2. 扫描仪没有名为nextD()的类。您可能正在寻找nextLine

  3. 在Java中,字符串包含在双引号"中,而不是单引号'。另外,为了比较字符串,你需要使用direction.equals(“string”)。看azurefrog的评论。

我假设你正在使用像Eclipse或IntelliJ(如果你不是,你可能应该)的IDE。用鼠标将鼠标悬停在红色部分上,它会告诉你它的抱怨。

-2

这里是你的代码的修正: -

int i=0; 
int b=0; 
if (i>=1 && b<=7){ /*you need to have variables for your int and u must 
define them before the if statment*/ 
Scanner sc = new Scanner(System.in); 
String direction; 
System.out.println("Enter your choice: "); 
direction=sc.next(); /*no D for Strings and .nextLine() if its separated by 
spaces*/. 
if (direction.equals("left")) { /*String uses .equals() method inside for 
comparing equal strings*/. 
    maze.push("left"); //String uses literals " " 
    System.out.println("Pushed left to stack"); 
}} 
+0

在这种情况下,变量不应该在if语句中声明。另外,你错过了一个关闭paren'if(direction.equals(“left”)' – alexgbelov

+0

感谢它真的有帮助 – Chiaki29

+0

我被拒绝了这个答案! –

0

int类型的变量a做到像if(a >=1 && a <=7)

相关问题