难以接收参与者的数据(字符串和数字)。我们的想法是创建一个程序,将数据输入数组(名称和时间分别),并最终按名称和时间分析数据
这是我的代码尝试......
import java.util.Scanner;
public class RaceTimes
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Athletic Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants ");
num=input.nextInt();
// If the user enters an invalid number... display error message... ask again for valid input number
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants...");
num=input.nextInt();
}
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
for (int i = 0 ; i < nameArray.length ; i++)
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
//nameArray [1] = input.nextString();
}
}
答案 0 :(得分:1)
你快到了!
for (int i = 0 ; i < nameArray.length ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
应该这样做。
您可能希望在此处添加一些内容以应对超出范围的值,或者不能解释为浮点数的内容。您需要try
/ catch
块来捕获InputMismatchException
才能正确处理输入无法解释为数字的内容的人。 (.nextDouble()
方法如果无法解析输入,则会抛出此异常。)