我是Java編程初學者,希望得到一些建議。 我創建了一個非常簡單的程序/應用程序,要求用戶輸入命令,然後在用戶指定的位置,大小和顏色上顯示圖形屏幕上的基本形狀。如何在使用java掃描器類時驗證用戶文本輸入?
我已經使用了掃描器類來獲得從鍵盤的用戶輸入(例如用戶類型移動100 150和圖形屏幕筆移動到X = 100,Y = 150或類型圈100顯示在指定的x,y座標處的圓半徑爲100)
我想在用戶輸入不正確的命令或嘗試輸入任何內容或隨機擊鍵時返回錯誤消息(例如,如果他們拼寫錯誤或沒有輸入爲該命令指定足夠的值)
在魔門t時的程序崩潰,必須重新啓動
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循環和其他我在各種網頁上找到的但沒有任何工作。
任何建議非常感謝。
使用else語句更新代碼 –
當您收到ArrayIndexOutOfBoundsException時,輸入什麼? – shevchyk