命令程序,大部分工作,到处都有错误



我正在编写一个程序来接收用户的命令,并相应地输出。程序不断要求输入,直到用户输入"退出"作为命令。

命令包括:

阶乘 #(将一个数字作为参数)

输出数字的阶乘,例如。

Factorial 5
5! == 120

GCD # # (接受 2 个数字作为参数)

输出 2 个数字之间的最大公约数(递归方式)。

gcd 5 10
gcd(5, 10) == 5

已排序 # #...(获取用户想要的任意数量的数字)检查命令后面的数字是否按顺序排列

。 例如。
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.

现在这一切都很好用。到目前为止,没有任何问题,当我输入一个字母而不是一个数字时,它应该尝试捕获一个 输入错配异常,这种工作。 例如。

如果用户输入一个字母,它会这样说。

Factorial j
Not a number: For input string: j

Factorial 5 j
5! == 120

它会按照正常的方式进行,但它将"j"作为下一个命令,因为如果我输入阶乘 5 退出,它会打印阶乘然后退出,我不知道为什么会发生这种情况。

另一件事是,如果参数对于命令来说太多,我想抛出并捕获异常,因此用户无法键入阶乘 5 10,它只会计算 5 的阶乘,它会打印一条错误消息,我不知道如何实现这一点。

这是我目前的代码。 回答 09.java

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* 
* 
* @author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
@SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "nGCD, and check to see if a list of numbers are in order"
+ "n-----------------------------------"
+ "nMade by Amr Ghoneim (A00425709)"
+ "n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "n - factorial #"
+ "n     The product of all numbers from 1 to #."
+ "n     (The argument must not be negative.)" + "n - gcd # #"
+ "n     The greatest common divisor of the two numbers."
+ "n     The biggest number that divides evenly into both of 
them."
+ "n - sorted #..."
+ "n     Whether the numbers are in order from smallest to 
largest."
+ "n     If not, then where the first out-of-order number is."
+ "n - help" + "n     This help message." + "n - quit"
+ "n     End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}

我缺少的是找出用户放置了多少参数,如果打印消息太多,对于排序命令,我无法让它打印用户输入的字母。 出于某种原因,当我输入"阶乘 5 5"时,会打印">>>"两次而不是一次。 这里和那里只有一些错误, 有人可以指导我如何处理这些东西,或者展示一些例子吗?

谢谢!

我已经修改了您的代码,以便它可以按照您的描述工作。只需查看代码注释即可了解详细信息。请随时发表评论以澄清。

修改后的代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "nGCD, and check to see if a list of numbers are in order" + "n-----------------------------------"
+ "nMade by Amr Ghoneim (A00425709)" + "n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "n - factorial #" + "n     The product of all numbers from 1 to #."
+ "n     (The argument must not be negative.)" + "n - gcd # #"
+ "n     The greatest common divisor of the two numbers."
+ "n     The biggest number that divides evenly into both of them." + "n - sorted #..."
+ "n     Whether the numbers are in order from smallest to largest."
+ "n     If not, then where the first out-of-order number is." + "n - help"
+ "n     This help message." + "n - quit" + "n     End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}

最新更新