如何接收 Array 的用户输入,然后用于绘制方法


package package13;
import java.awt.Graphics;
import java.util.Scanner;
import javax.swing.JApplet;
public class BarChartApplet extends JApplet {

    final int baseX=30;
    final int baseY=100;
    final int width=10;
    final int space=30;
    //int height[]={30,20,40,90};
    int height[]=new int[4];
    System.out.println("Enter 4 heights of the bars");
    Scanner scan = new Scanner (System.in);
    for (int k=0;k<height.length;k++) {
    height[k]=scan.nextInt();
    }
    int upperLeftX;
    int upperLeftY;

    public void paint(Graphics g) {
        g.drawLine(5, 100, 200, 100);
        for (int i=0;i<height.length;i++) {
            upperLeftX=baseX+i*(width+space);
            upperLeftY=baseY-height[i];
            g.fillRect(upperLeftX,upperLeftY,width,height[i]);
        }
    }
}}

我正在尝试获取数组值的用户输入。我使用这些数组的值,然后用于为我正在创建的条形图中的条形设置高度。我遇到的问题是,当我尝试创建一个System.out.print来要求用户输入值时,我收到错误,因为我没有在(公共静态空隙主(下使用它,但是当我尝试添加公共静态空洞主时,我得到一个错误油漆方法。

任何帮助将不胜感激。

这是学习Java的常见问题。必须声明一个public static void main(String[] args){}方法,因为这是应用程序开始执行的位置。您可以将此方法视为独立于您的类。它仍然必须在类中声明,但您可以在任何类中声明该方法并使用它执行操作,不同之处在于,如果您在另一个类中声明它,则必须从该类执行程序。

为了在main中使用类中的方法,您可以执行以下两项操作之一:

将方法声明为静态。这意味着该方法不直接与该类的任何一个对象相关联,而只是类本身的一部分。所以如果你有一个类:

public class Apple{
    public void eat(){}
    public static void describe(){}
}

然后你必须有一个特定的new Apple yourApple().eat();吃,但你可以通过Apple.describe();来描述任何苹果。事实上,这个例子有点虚构,因为在现实生活中你可以描述任何一个特定的苹果和一个普通的苹果,但在这种java情况下,你只能描述一个普通的苹果,如果你去new Apple yourApple().describe();它将等同于Apple.describe()

这种使用方法的静态方式很难在大型项目中扩展,因为它试图绕过 java 的类格式,但它是制作简单示例的好方法。我已经展示的第二种方式称为实例化,它的工作原理是在主类中创建一个Apple并在其上调用方法:

public class Apple{
    public static void main(String[] args){
        Apple apple = new Apple();
        Apple.eat();
    }
    public void eat(){
        System.out.println("Nom");
    }
}

我希望这有所帮助。

你需要把你的代码放到一个方法中。 方法是您唯一可以执行的内容。 main方法是任何 Java 程序的入口点。 它必须是静态的,因为还不能存在任何实例。

这段代码特别需要包装到 main 中:

public static void main(String[] args) {
    int height[]=new int[4];
    System.out.println("Enter 4 heights of the bars");
    Scanner scan = new Scanner (System.in);
    for (int k=0;k<height.length;k++) {
        height[k]=scan.nextInt();
    }
}

我还注意到,你从来没有真正叫过油漆。 我不确定在这里建议什么,因为我不知道你想做什么。 您希望它如何/为什么运行?

相关内容

最新更新