输入到数组的命令以“退出”字

时间:2018-10-25 00:11:44

标签: java arrays io

我需要做Football Results Generator。我创建了4个数组,每个数组包含10个元素,但是我需要包含一个循环,该循环允许用户改变主意并在一定数量的条目后键入“ quit”来停止输入。您能帮忙吗-我是编程新手,所以它一定很简单。

import java.util.Scanner;//

public class Football_Results_Generator
{
    public static void main(String[] args) 
    {
        Scanner kbd = new Scanner (System.in);


        String[] HomeTeam = new String[10];
        String[] AwayTeam = new String[10];
        int[] HomeScore = new int[10];
        int[] AwayScore = new int[10];

        int index = 0;
        int sum = 0;
        int sum1 = 0;

        do 
        {
            System.out.print("Enter Home Team Name: ");
            HomeTeam[index] = kbd.nextLine();
            System.out.print("Enter Away Team Name: ");
            AwayTeam[index] = kbd.nextLine();
            System.out.print("Enter Home Team Score:");
            HomeScore[index] = kbd.nextInt();
            System.out.print("Enter Away Team Score: ");
            AwayScore[index] = kbd.nextInt();
            kbd.nextLine();


        } while(index < 10);
        index = 0;

        System.out.println();   

        do 
        {
            System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
            index = index + 1;

        } while(index < 10);

        kbd.close();

        for(index = 0; index < 10; index++)
            sum += HomeScore[index];
            for(index = 0; index < 10; index++)
                sum1 += AwayScore[index];

        System.out.println();
        System.out.println("Totals");
        System.out.println("-------------------------------");
        System.out.println("Total number of matches played: " + index);
        System.out.println("Total of all home scores: " + sum);
        System.out.println("Total of all away scores: " + sum1);
        System.out.println("Total number of draws: ");
        System.out.println("The highest home score: ");
        System.out.println("The highest away score: ");

    }
}

1 个答案:

答案 0 :(得分:1)

  

允许用户改变主意并在5次尝试后输入quit来停止输入。

使用临时变量捕获字符串输入:

String line;
do 
{
    System.out.print("Enter Home Team Name: ");
    line = kbd.nextLine();
    if("quit".equalsIgnoreCase(line)){
        break;
    }
    HomeTeam[index] = line;
    .....
    index = index + 1; //missed
}while(index < 10);
index = 0;

在这里,"quit".equalsIgnoreCase(line)将确保line的情况不被关注,例如“退出”,“退出”,“退出”等将导致true

  

整数输入数组怎么样?是同一概念吗?

好吧,如果输入既不是quit也不是int,则需要处理异常:

line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
    break;
}
try{
    HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
    //Error conversion string to int
}