我的第二个java课程完成后,我一直在尝试自己的东西。很难回到开头并记住如何使用我过去几个月学到的所有东西,所以我正在尝试制作一个程序,询问用户他们想要绘制的形状(基于使用的基本形状) for循环,这基本上是我在编程中学到的第一件事),以及作为int的形状大小。
我已经设置了扫描仪,但是我不记得size变量必须如何/在哪里才能在我的“draw”方法中使用它。基本上,我尝试过不同的东西,但“尺寸”总是遥不可及。到目前为止,这是我的代码(我已经排除了实际绘制形状的代码,但它们都涉及以int size作为变量的循环):
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a shape!");
String shape = input.nextLine();
System.out.println("Choose a size!");
int size = input.nextInt();
}
public static void drawCirlce() {
//Code to draw a circle of size given input into scanner.
}
public static void drawSquare() {
//Code to draw a square of size given input into scanner.
}
public static void drawTriangle() {
//Code to draw a triangle of size given input into scanner.
}
public static void drawRocket() {
//Code to draw a rocket of size given input into scanner.
}
}
非常感谢大家!我会继续四处寻找,但任何提示都非常受欢迎。
答案 0 :(得分:1)
您可以将size变量传递给绘图方法,如下所示:
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a shape!");
String shape = input.nextLine();
System.out.println("Choose a size!");
int size = input.nextInt();
// Choose what shape you want to draw
drawCircle(size);
// or
drawSquare(size);
// or
drawTriangle(size);
// etc...
}
public static void drawCirlce(int size) {
//Code to draw a circle of size given input into scanner.
}
public static void drawSquare(int size) {
//Code to draw a square of size given input into scanner.
}
public static void drawTriangle(int size) {
//Code to draw a triangle of size given input into scanner.
}
public static void drawRocket(int size) {
//Code to draw a rocket of size given input into scanner.
}
}
答案 1 :(得分:0)
您需要在类级别声明变量。此外,由于您使用的是所有static
方法,因此这些变量也需要声明为static
public class Practice {
private static String shape;
private static int size;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a shape!");
shape = input.nextLine();
System.out.println("Choose a size!");
size = input.nextInt();
}