【问题标题】:X can not be resolved to a variable in a for loop; Eclipse, JavaX 无法解析为 for 循环中的变量;日食,Java
【发布时间】:2017-02-02 01:05:46
【问题描述】:

我刚开始使用 Java,遇到了一个我不理解的错误。我已经看过并且无法在另一个问题中找到我的答案,如果这是重复的话,我深表歉意。

我的代码是:

public class Welcome {
public static void main(String[] args) {
    System.out.println("x\t x^2\t x^3");
    for(int x = 1; x < 5; x++)
        System.out.println(x);
        System.out.println("\t");
        System.out.println(x * x);
        System.out.println("\t");
        System.out.println(x * x * x);
    }
}

在第一次打印时通过x 代码将运行良好,但在随后的行中,x * x 和x * x * x 的行为就像未定义x。我怎样才能让这段代码运行,我的错误背后的原因是什么?

谢谢。

【问题讨论】:

  • 在for(int x = 1; x &lt; 5; x++) { 中添加一个左大括号,在System.out.println(x * x * x); } 之后添加一个右大括号
  • 啊啊啊,谢谢你:)

标签: java eclipse for-loop int


【解决方案1】:

你忘了在这里输入 if 的范围

如果没有指定开始和结束花括号,它只会运行第一个 println

for(int x = 1; x < 5; x++)
{
    System.out.println(x);
    System.out.println("\t");
    System.out.println(x * x);
    System.out.println("\t");
    System.out.println(x * x * x);
}

你是代码

for(int x = 1; x < 5; x++)    
    System.out.println(x);        //if you didn't specified the begin and end curly brace 
                                  //for range . this is the only line will work for it
    System.out.println("\t");     //from this line, x now is undefined
    System.out.println(x * x);    //*
    System.out.println("\t");     //*
    System.out.println(x * x * x);//until here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2020-04-19
    • 2020-10-05
    相关资源
    最近更新 更多