简体   繁体   English

如何在循环中打印出方法

[英]How do I print out a method within a loop

I apologize but I am new to programming and I'm having difficulty coding a program. 抱歉,我是编程新手,我在编写程序时遇到困难。 The original program is as follows: 原始程序如下:

import java.io.*;
import java.io.IOException;
import java.io.InputStreamReader;

class buildABoat{

    String boatName;      // Boat name
    void buildABoat(){      
        String BoatName;            
    }

    void nameTheBoat() {        
        try {           
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\n\nWhat should we name this vessel? \n\n");
            this.boatName = br.readLine();
            System.out.println("\n\nThe " + boatName + " is ready to sail!\n");             
        }           
        catch (IOException e) {                 
        }   
    }
}

class proj1{

    public static void main(String[] arg){

        buildABoat boat1;
        buildABoat boat2;
        buildABoat boat3;
        buildABoat boat4;
        buildABoat boat5;

        boat1 = new buildABoat();
        boat2 = new buildABoat();
        boat3 = new buildABoat();
        boat4 = new buildABoat();
        boat5 = new buildABoat();

        boat1.nameTheBoat();
        boat2.nameTheBoat();
        boat3.nameTheBoat();
        boat4.nameTheBoat();
        boat5.nameTheBoat();

        System.out.println("(Press ENTER to exit)");

        try {           
            System.in.read();
        }           
        catch (IOException e) {         
            return;
        }
    }
}

This produces the following: 这将产生以下结果:

What should we name this vessel?
Enterprise
The Enterprise is ready to sail!
What should we name this vessel?
Columbia
The Columbia is ready to sail!
What should we name this vessel?
Challenger
The Challenger is ready to sail!
What should we name this vessel?
Atlantis
The Atlantis is ready to sail!
What should we name this vessel?
Endeavor
The Endeavor is ready to sail!
(Press ENTER to exit)

I tried to change this to the following: 我试图将其更改为以下内容:

import java.io.*;
import java.io.IOException;
import java.io.InputStreamReader;

class buildABoat{    
    String boatName;      // Boat name

    void buildABoat(){
        String BoatName;
    }

    void nameTheBoat() {
        try {           
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\n\nWhat should we name this vessel? \n\n");
            this.boatName = br.readLine();
            System.out.println("\n\nThe " + boatName + " is ready to sail!\n");             
        }           
        catch (IOException e) {                 
        }   
    }
}

class proj1{

    public static void main(String[] arg){

        Boat[] boat;            
        boat = new Boat[5];    
        for(int i = 0; i <= Boat.Length; i++){          
            nameTheBoat();          
        }           
        System.out.println("(Press ENTER to exit)");

        try {           
            System.in.read();
        }           
        catch (IOException e) {         
            return;
        }
    }
}

This of course produces the following error: 当然,这会产生以下错误:

proj1.java:71: error: cannot find symbol
                for(int i = 0; i <= Boat.Length; i++){
                                        ^
  symbol:   variable Length
  location: class Boat
proj1.java:73: error: cannot find symbol
                        nameTheBoat();
                        ^
  symbol:   method nameTheBoat()
  location: class proj1
2 errors

What am I missing in the new program? 我在新程序中缺少什么?

使用小写长度

for(int i = 0; i <= Boat.length; i++)

Try doing boat.nameTheBoat() instead of just nameTheBoat() 尝试做boat.nameTheBoat()而不只是nameTheBoat()

Also

for(int i = 0; i <= boat.length; i++){          
        boat[i].nameTheBoat();          
    }    

boat is the instance of the class Boat (probably should be buildABoat ). boat是Boat类的实例(可能应该是buildABoat )。 These look like they're compiler errors and not runtime errors, so the compiler should give you some hint (as it does) as to the exact line numbers. 这些看起来像是编译器错误,而不是运行时错误,因此,编译器应向您提供一些有关确切行号的提示(确实如此)。

You must try to calculate the length on the object rather than the class. 您必须尝试计算对象而不是类的长度。 So, it should be boat.length, where boat is your object here 因此,应该是boat.length,这里的船是您的对象

You call a method using the class name, if the method is a static method. 如果该方法是静态方法,则使用类名调用方法。

As Nurlan mentions, the first error is because you're using a capital L for the length property of an array. 正如Nurlan提到的那样,第一个错误是因为您将大写L用作数组的length属性。 The actual property begins with a lowercase l. 实际属性以小写l开头。

The second error is because the method nameTheBoat is part of the class named buildABoat , but you're trying to invoke it as if it were part of your main class. 第二个错误是因为方法nameTheBoat是名为buildABoat的类的一部分 ,但是您试图像将其作为主类的一部分一样对其进行调用。 You need an instance of a buildABoat object in order to invoke this method. 您需要一个buildABoat对象的实例才能调用此方法。

One other suggestion: to comply with java naming conventions, you should NOT begin the name of a class with a lowercase letter. 另一个建议:为了遵守Java命名约定,您不应以小写字母开头类的名称。 Classes should always start with a capital letter. 上课应始终以大写字母开头。 Methods should always begin with a lowercase letter. 方法应始终以小写字母开头。

where you have 你在哪里

nameTheBoat();

in your for() loop you need to have 在for()循环中,您需要

boat[i] = new Boat();
boat[i].nameTheBoat();

The reasons are: 1) nameTheBoat() is a method that only operates on objects of type Boat . 原因是:1) nameTheBoat()是一种仅对Boat类型的对象进行操作的方法。 You are not giving it any object to work on. 您没有给它任何要处理的对象。 2) boat[] = new Boat[5]; 2) boat[] = new Boat[5]; initializes an Array object, but doesn't create the 5 new Boat s in the Array object. 初始化数组对象,但不建立5个新Boat在S Array对象。 So you need to create each of those 5 Boat s before you can run a Boat method on them. 因此,您需要先创建这5个Boat然后才能对它们运行Boat方法。 Otherwise you'll get a null pointer error. 否则,您将得到一个空指针错误。

EDIT: and of course as others mentioned, boat.length is the length of the array boat , boat.Length is wrong. 编辑:当然,正如其他人提到的那样, boat.length是数组boatboat.Length的长度。

Enjoy! 请享用!

The object array you have created is boat = new Boat[5]; 您创建的对象数组是boat = new Boat[5]; . Ideally you whole code should be like this 理想情况下,整个代码应该像这样

Boat[] boat = new Boat[5];    
for(int i = 0; i <= Boat.Length; i++){          
boat[i] = new Boat();
boat[i].nameTheBoat();          
}

You have a few problems. 你有几个问题。

One is that boat as an array 一个是boat作为一个阵列

Boat[] boat;            
boat = new Boat[5];    
for(int i = 0; i <= Boat.Length; i++){          
    nameTheBoat();          
} 

To access the array length it would be boat.length instead of what you have. 要访问数组的length ,将是boat.length而不是您拥有的length

The next problem I see is your call to nameTheBoat() . 我看到的下一个问题是您对nameTheBoat()调用。 That method is part of the buildABoat class. 该方法是buildABoat类的一部分。

This code looks like a constructor with accident. 这段代码看起来像一个偶然的构造函数。

class buildABoat{    
    String boatName;      // Boat name

    void buildABoat(){
        String BoatName;
    }

If void buildABoat () would be a method (void says so), why would you declare a local variable in it, and not use it? 如果void buildABoat()将是一个方法(void这样说),为什么要在其中声明局部变量而不使用它呢?

And don't repeat the name of a well named attribute as comment. 并且不要重复使用命名良好的属性的名称作为注释。

class BuildABoat {    
    private String boatName;   

    public BuildABoat (String name) {
        boatName = name;
    }

This would make some sense. 这将是有道理的。 You now have a class, which can be instantiated by passing a boatname, which is preserved in the class. 现在,您有了一个类,可以通过传递保留在该类中的船名进行实例化。

In your Proj1-Class, you split declaration and initialisation. 在Proj1-Class中,您可以拆分声明和初始化。 This is a bad habit. 这是个坏习惯。 Sometimes it's not avoidable, but if it is, avoid it. 有时这是不可避免的,但如果可以避免,那就避免它。

class Proj1 {

    public static void main(String[] arg){

        BuildABoat [] boat = new BuildABoat[5];    
        for(int i = 0; i <= boat.length; i++) {
            // to make this work, we have to change the 
            // buildABoat
            boat[i] = new BuildABoat (BuildABoat.nameTheBoat ());
        }
        System.out.println ("(Press ENTER to exit)");
        try {           
            System.in.read ();
        }           
        catch (IOException ignored) {         
            return;
        }
    }
}

The method nameTheBoat has to be static, if we call it without actually having a (builda)boat already. 如果我们在实际上没有(builda)boat的情况下调用它,则方法nameTheBoat必须为静态。

public static String nameTheBoat () {
    try {           
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println ("\n\nWhat should we name this vessel? \n\n");
        String s = br.readLine ();
        System.out.println ("\n\nThe " + s + " is ready to sail!\n");
        return s;
    }
      catch (IOException e) {
        return "";
    }   
}

I hope the code does a little what you intended. 我希望代码能达到您的预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在方法中打印结果? - How do I print out the result in a method? 如何更改myDate1的值并在主方法中打印出该新值? - How do i change the value of myDate1 and print out that new value within my main method? 如何从方法中获取变量并将其打印在main中? - How do I get a variable out of a method and print it in main? 我该如何打印出来? - How do i print this out? 如何在java查询的循环中打印“resultList”并使用javascript打印出来? - how do i print a “resultList” in a loop from java query and also print it out using javascript? 如何将此语句(在while循环中)不打印两次到控制台? - How can I make this statement (within a while-loop) not print out twice to the console? 如何防止 For 循环继续循环,直到循环中调用的方法完成? - How do I prevent a For loop from continuing to loop, until a method called within the loop, is complete? 如何让我的程序从 do while 循环中打印出我的所有输入? - How do I get my program to print out all of my input from a do while loop? 如何在方法中为变量设置值并在main方法中将其打印出来? - How do I set a value to a variable in a method and print it out in the main method? 当我在循环中打印数字时,如何删除最后一个逗号? - How do i remove the last comma when i print numbers within a loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM