1

我是 Java 编程的初学者,正在寻找一些建议。我创建了一个非常简单的程序/应用程序,要求用户输入命令,这些命令依次在图形屏幕上以用户指定的位置、大小和颜色显示基本形状。

我已经使用扫描仪类从键盘获取用户输入(例如,用户类型move 100 150并且图形屏幕移动到 X = 100,Y = 150 或类型circle 100以在指定的 x,y 处显示圆半径 100协调)

如果用户输入了不正确的命令或尝试输入任何内容或随机击键(例如,如果他们拼错命令或没有为命令指定足够的值),我想返回错误消息

目前程序崩溃,必须重新启动

import java.util.Scanner;


public class Assign1 {


public final static void main(String [] args) {

    System.out.println("Let's draw something on the screen!");

    GraphicsScreen graphics = new GraphicsScreen();

Scanner input = new Scanner(System.in); // used to read the keyboard

    String next;    // stores the next line input
    String[] one;

    do {
        System.out.print("Enter a command (\"stop\") to finish : ");
        System.out.print("Type 'help' for a list of commands ");
        next = input.nextLine();
        one = next.split(" ");

        String command = one[0];

        if(next.contains("help")) {
            System.out.println("Type 'move' followed by an X and Y co-ordinate to move the graphical pointer.");
            System.out.println("Type 'circle' followed by a radius value to output a circle.");
            System.out.println("Type 'line' followed by an X and Y co-ordinate to draw a line.");
            System.out.println("Type 'clear' to reset the graphical canvas.");
        }


        if(next.contains("move")) {

            int x = 0;

            int y = 0;

            x = Integer.parseInt(one[1]);

            y= Integer.parseInt(one[2]);

            graphics.moveTo(x, y);

        } 



        if( command.equalsIgnoreCase("circle")) {


            int radius = 0;


            radius = Integer.parseInt(one[1]);


            graphics.circle(radius);

        } 


        if(command.equalsIgnoreCase("line")) {

            int x = 0;
            int y = 0;

            x = Integer.parseInt(one[1]);

            y= Integer.parseInt(one[2]);

            graphics.lineTo(x,y);

        }


        if(next.contains("clear")) {
            graphics.clear();
        }

    } while ( next.equalsIgnoreCase("stop") == false );

    System.out.println("You have decided to stop entering commands. Program terminated!");

    graphics.close();

我在另一个名为

graphicscreen.java

我只是在寻找有关如何验证用户文本输入的建议,以便在键入除我的特定命令之一之外的任何内容时给出错误消息。

我尝试过使用 if 语句和 while 循环以及我在各种网页上找到的其他语句,但还没有一个起作用。

任何建议都非常感谢。

4

2 回答 2

0

使用nested if-else而不是only if.

 if(command1istrue){
  }
else if(command2istrue){

 }
else if(command3istrue){
}
else {
system.out.println("Error you have entered the wrong command");
}

在这里检查

于 2012-10-31T20:53:52.197 回答
0

使用else ifelse。只有当它上面的所有and条件评估为 时,else if才会检查一个条件。只有当它上面的所有和条件评估为时,一个块才会运行。ifelse iffalseelseifelse iffalse

if(next.contains("move")) {
} 
else if( command.equalsIgnoreCase("circle")) {
} 
else if(command.equalsIgnoreCase("line")) {
}
else if(next.contains("clear")) {
}
else {
 //input invalid
}
于 2012-10-31T20:54:25.053 回答