在java中编译99瓶代码时出错

时间:2017-10-19 07:08:44

标签: java compilation

我是Java的新手程序员(或至少试图成为一名),我的代码存在一些问题。

这首歌叫99瓶啤酒,从99到0,然后停止。代码:

public class 99bottles {

public static void main (String[] args) {

    String word = "bottles";
    x bottle = 99;

    for (int i==0; i<99; i--) {
        if (i == 1) {
            word = "bottle";
        }

        System.out.println();
        System.out.println(i+ "Bottles of beer on the wall, " + i + " bottles of beer.");

        int y = i - 1 ;
        System.out.println("Take one down and pass it around, " + y + " bottles of beer on the wall.");



    }
}

}

然而,只要我尝试编译它,我就会收到看似不合逻辑的错误。 这里 Screenshot

在决定前往这里寻求帮助之前,我正把头靠在墙上。

6 个答案:

答案 0 :(得分:1)

您的代码中存在大量语法错误:

  • 班级名称不能以数字
  • 开头
  • x似乎不是有效类型:x bottle = 99;
  • for圈中的错误条件:int i==0

还有语义错误:

  • for (int i==0; i<99; i--) - 从0递减并检查是否小于99,这是一个无限循环

答案 1 :(得分:1)

您需要对代码进行一些更改:

您可以删除:

x bottle = 99;

你的循环应该是for (int i = 99; i > 0; i--) {

将变量传递给println语句:

System.out.println(i + " " + word + " of beer on the wall, " + i + " " + word + " of beer.");

答案 2 :(得分:0)

两次更改(未检查代码的逻辑):

1)x bottle = 99;int bottle = 99;

2)for (int i==0; i<99; i--)for (int i=0; i<99; i--)

==表示比较,=用于指定值

x bottle = 99定义您需要使用类型的变量。

<强> 编辑:

班级名称不能以数字

开头

答案 3 :(得分:0)

以下是您尝试执行的清理版本:

for (int i = 99; i > 0; i--) {
    String bottle = "bottle" + i > 1 ? "s" : "";
    System.out.println(i + bottle + " of beer on the wall, " + i + bottle + " of beer.");
    System.out.println("Take one down and pass it around, " + y + bottle + " of beer on the wall.");
}

您当前的代码充满了问题,包括:

  • 班级名称不能以数字
  • 开头
  • i == 0没有为循环计数器赋值,它会对它进行比较;而是使用i = 0
  • x bottle = 99;这似乎只是悬而未决的代码,你的代码甚至不应该立即编译
  • 当你的计数达到一个时,你确实正确地找到了bottle这个词需要单数的边缘情况;但你从来没有完全实现它,q.v。上面的代码片段是一种可行的方法

答案 4 :(得分:0)

以下是您的工作代码:(只需复制并使用!)

public static void main (String[] args) {

    String word = "bottles";
   // x bottle = 99;

    for (int i=0; i<=99; i++) {
        if (i == 1) {
            word = "bottle";
        }

        System.out.println();
        System.out.println((99-i)+ " Bottles of beer on the wall, " + (99-i) + " bottles of beer.");

        int y =99 - 1 ;
        System.out.println("Take one down and pass it around, " + y + " bottles of beer on the wall.");



    }
}

答案 5 :(得分:0)

Luke非常好answer,请仔细检查循环条件。

for (int i = 0 ; i < 99 ; i--)表示你从一个整数&#39; 0&#39;开始,然后你继续递减0,直到i不小于99.但是如果你继续减少0,你将永远得到一个小于99的数字,因此你的结束条件永远不会实现。

您可以做两种选择:

for (int i = 0; i < 99 ; i++)

for (int i = 99; i > 0 ; i--)

这主要是语法或语义相关的错误,如卢克所说。

相关问题