1

Javaでメニューを利用したプログラムを作成しようとしています。ただし、forループを使用してユーザー入力を文字列配列に読み取るのに少し問題があります。配列を String から int に変更すると、コードは正常に動作します。しかし、文字列に変更すると、ユーザーがチーム名を入力する前にループが 2 回発生します。また、入力したいチームの数に応じてユーザーが配列のサイズを制御できるようにする必要もあります。そのため、5 チームと入力したい場合、配列のサイズは 5 になります。ユーザーが入力する前に配列を宣言すると、配列サイズの場合、機能しません。そして、if ステートメント内にそのままにしておくことはできません。そうしないと、スコープの問題が発生します。誰でもこれを回避する方法を見ることができますか? これがプログラムの最初のビットです

import java.util.Scanner;

public class main {


public static void main(String[] args) {

    System.out.println("Howdy sports fan!");

    String menuSelect;

    do {
        System.out.println("Please pick an option from the list below:");
        System.out.println("1) Create League");
        System.out.println("2) List all teams");
        System.out.println("3) Record a win");          
        System.out.println("4) Record a loss");         
        System.out.println("5) Quit");          
        Scanner keyboard = new Scanner(System.in);
        menuSelect = keyboard.nextLine();

        if ( menuSelect.equals("1") )
        {
            System.out.println("How many teams should I make?");
            String[] teamsArray= new String[keyboard.nextInt()];

            for ( int i = 0; i < teamsArray.length; i++ )
            {
                System.out.println("Team " + (i+1) + "'s name?");
                teamsArray[i] = keyboard.nextLine();                
            }
        }

    } while(!menuSelect.equals("5"));

}
4

1 に答える 1

1

あなたのコードにはいくつかの問題があり、以下のように修正しようとしました:

import java.util.Scanner;
import java.util.*;

public class SportsLeague { 

  public static void main(String[] args) {

    System.out.println("Howdy sports fan!");

    String menuSelect;
    Scanner keyboard = new Scanner(System.in);
    List<String> teamsArray = new ArrayList<String>();

    do {
      System.out.println("Please pick an option from the list below:");
      System.out.println("1) Create League");
      System.out.println("2) List all teams");
      System.out.println("3) Record a win");          
      System.out.println("4) Record a loss");         
      System.out.println("5) Quit");          

      menuSelect = keyboard.nextLine();

      //since you're making a menu, switches are better
      //this is especially so since your program exceeds 4 options
      //which is a generic rule of thumb for readability
      switch(menuSelect) {
        case "1":
          System.out.println("How many teams should I make?");

          //reset the teamsArray, so that you can create a new league
          //you may want to change this if you want
          teamsArray.clear();

          //get the number of teams with which to create names for
          //by converting the line from the keyboard to an integer
          int teams = Integer.parseInt(keyboard.nextLine());

          //now iterate over it and assign values to the array by
          //prompting the user for the info and saving it using
          //the add() method
          for ( int i = 0; i < teams; ++i )
          {
            System.out.println("Team " + (i+1) + "'s name?");
            teamsArray.add(keyboard.nextLine());    
          }
          break;//break is required here

        //print out the contents of the teamsArray
        case "2":
          for ( int i = 0; i < teamsArray.size(); ++i )
          {
            //print out the elements within the arraylist using the "get()" method
            System.out.println(teamsArray.get(i));   
          }
          break;

         //implement for the other options...
      }
    } while(!menuSelect.equals("5"));
  }
}

1つ: 「main」という名前のクラスがありました。境界線は問題ありませんが、大文字にする必要があります。ただし、問題にもっと適切な名前に自由に名前を変更しました。

2:可能であれば、「通常の」配列の代わりに ArrayLists を使用する必要があります。通常の配列を使用する場合よりも、メモリやその他のオプションを再割り当て、解放するためです。

3:ケースの数が 4 を超えるため、 switch を使用する必要があります (これは、読みやすくするためにメニュー コードを記述するときの一般的な経験則です)。

それらはさておき、これはあなたの問題に非常にうまく合うはずだと思います。

あなたの場合、ループはkeyboard.nextInt(). 整数は正しく読み取れましたが、改行文字が読み取られていませんでした。したがって、keyboard.nextLine()が呼び出されると、改行文字が読み取られます。これにより、「2 回」ループし、2 番目の出力を取得していないという印象がありました (実際にはループがあったが、知らなかった、または が表示されなかった場合)。これが、文字列として持っていたときに改行文字をキャプチャし、キャプチャが問題なく機能した理由でもあります。

アップデート:

静的配列と ArrayList を使用するように編集:

import java.util.Scanner;
import java.util.*;

public class SportsFan3 { 

  public static void main(String[] args) {

    System.out.println("Howdy sports fan!");

    String menuSelect;
    Scanner keyboard = new Scanner(System.in);

    String[] teamsArray = new String[0];

    do {
      System.out.println("Please pick an option from the list below:");
      System.out.println("1) Create League");
      System.out.println("2) List all teams");
      System.out.println("3) Record a win");          
      System.out.println("4) Record a loss");         
      System.out.println("5) Quit");          

      menuSelect = keyboard.nextLine();

      switch(menuSelect) {
        case "1":

          //set the number of teams within array to 0

          //check to see that the number of teams that the user has enetered does not exceed the maximumTeamsize

          int numteams = 0;

          System.out.println("How many teams should I make?");   
          numteams = Integer.parseInt(keyboard.nextLine());

          teamsArray = new String[numteams];

          for ( int i = 0; i < teamsArray.length; ++i )
          {
            System.out.println("Team " + (i+1) + "'s name?");
            teamsArray[i] = keyboard.nextLine(); 
          }
          break;

        case "2":
          for ( int i = 0; i < teamsArray.length; ++i )
          {
            System.out.println(teamsArray[i]);   
          }
          break;

         //implement for the other options...
      }
    } while(!menuSelect.equals("5"));
  }
}
于 2013-03-09T06:31:52.210 に答える