我刚刚完成了这个我必须上课的课程。该程序应该从用户那里获得“ID”和“日”的输入,并且我的老师要求我们在这两个部分中放置一个循环以防用户没有输入正确的ID /日。我已将程序编写到可以接受输入的位置,但是如果输入有效或无法区分,它将无法区分,并将继续执行程序的其余部分。同样在数组的末尾,它应该打印数组,我已经完成了。我只想将ID(A,B,C,D)放在数组旁边。我希望最终结果是向下列出的数组左侧的ID与4x5表对齐。如果你们有任何关于如何做到的建议/提示,我们将不胜感激。
import java.util.Scanner;
public class Salesman
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
char[] names = {'A', 'B', 'C', 'D'};
char[] days = {'M', 'T', 'W', 'H', 'F'};
double[][] week = new double[4][5];
int stop = 0;
char nameInput;
char dayInput;
double cost;
int row;
int column;
do
{
System.out.println("Enter the salesman ID as A, B, C or D.");
String nameString = input.nextLine();
nameInput = nameString.charAt(0);
row = rowSearch(names, nameInput);
System.out.println("Enter the day of the week as M, T, W, H, or F");
String dayString = input.nextLine();
dayInput = dayString.charAt(0);
column = columnSearch(days, dayInput);
System.out.println("Enter the amount of the sale");
cost = input.nextDouble();
week[row][column] = cost;
System.out.println("Is there more data? Enter Y for more or N to stop");
input.nextLine();
String dataString = input.nextLine();
char dataInput = dataString.charAt(0);
if (dataInput == 'N')
{
stop = -1;
}
else
{
stop = 1;
}
}
while (stop >= 0);
System.out.println(" M T W H F");
for (row = 0; row < week.length; row++)
{
for (column = 0; column < week[row].length; column++)
{
System.out.printf("$%1.2f ", week[row][column]);
}
System.out.println();
}
}
public static int rowSearch(char[] names, char idInput)
{
int row = 0;
for (int i = 0; i < names.length; i++)
{
if (idInput == names[i])
row = i;
}
return row;
}
public static int columnSearch(char[] days, char columnInput)
{
int column = 0;
for (int i = 0; i < days.length; i++)
{
if (columnInput == days[i])
column = i;
}
return column;
}
}
答案 0 :(得分:0)
首先编写一个或多个方法,这些方法可以提示用户输入某些内容,并且可以自行验证响应。这些方法应该继续循环,直到给出有效响应(或输入一些退出代码)。
例如......
public String ask(String prompt, char... validResponses) {
String response = null;
String testResponses = String.valueOf(validResponses).toLowerCase();
Scanner input = new Scanner(System.in);
do {
System.out.println(prompt);
response = input.nextLine();
} while (!testResponses.contains(response.toLowerCase()));
return response;
}
然后你可以简单地用你需要的信息调用方法......
String response = ask("Enter the salesman ID as A, B, C or D.", 'A', 'B', 'C', 'D');
然后你会像往常一样使用响应......
此示例使用单个方法,该方法接受提示和有效字符列表。您可以轻松编写两个单独的方法来处理各个请求......
nameInput = askForSalesMan();
dayInput = askForDay();
但这归结为你认为最能处理的......