0

翌年の「ピアアドバイス」の予算を、今年に基づいて決めるのに役立つプログラムを書く必要があります。ユーザーは、彼らに支払う金額を決定するために、ピアアドバイザーの名前と彼らの最高の獲得度を尋ねられます。JOptionPaneの代わりにを使用しておりScanner、も使用していArrayListます。

ユーザーが名前と学位の両方を1つの入力にすべて入力し、それらを2つの異なる値として保存する方法はありますか、それとも2つの別々の入力ダイアログが必要になるのでしょうか。例:特定の給与を計算するために、名前を「Name1」、学位を「Degree1」として保存します。

また、私は使用してArrayListいますが、リストには最大6つの要素を含める必要があることを知っていますが、私がやろうとしていることを実行するためのより良い方法はありますか?

必要に応じて、これについて考え始める前に私が持っていたものは次のとおりです。

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class PeerTutoring
{
    public static void main(String[] args)
    {
        ArrayList<String> tutors = new ArrayList<String>();

        for (int i = 0; i < 6; i++)
        {
            String line = null;
            line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
            String[] result = line.split("\\s+");
            String name = result[0];
            String degree = result[1];
        }
    }
}
4

2 に答える 2

1

「ユーザーが名前と学位の両方を1つの入力にすべて入力する方法はありますが、それらを2つの異なる値として保存します。」

はい。たとえば、スペースで区切って入力を入力し、結果を分割するようにユーザーに依頼できます。

String[] result = line.split("\\s+"); //Split according to space(s)
String name = result[0];
String degree = result[1];

これで、2つの変数に入力があります。

「ArrayListを使用することにしましたが、入力される名前の数(6)を知っています。使用するより適切な配列メソッドはありますか?」

ArrayListは問題ありませんが、長さが固定されている場合は、固定サイズの配列を使用できます。


OPアップデートについて

あなたはそれを間違ってやっています、これはこのようになるはずです:

ArrayList<String[]> list = new ArrayList<String[]>(6);
String[] splitted;
String line;
for(int i=0;i<6;i++) {
    line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
    splitted = line.split("\\s+");
    list.add(splitted);
}

for(int i=0;i<6;i++)
    System.out.println(Arrays.deepToString(list.get(i))); //Will print all 6 pairs

ArrayList入力を表す文字列配列を含むを作成する必要があります(ユーザーが入力としてペアを入力するため)。さて、あなたがしなければならないのは、このペアをに挿入することだけですArrayList

于 2013-03-18T20:17:28.730 に答える
0

JOptionPaneからの入力を文字列に格納してから、文字列を配列に分割して、入力した名前と度を格納することができます。例えば:

String value = null;
value =  JOptionPane.showInputDialog("Please enter tutor name and 
                 their highest earned degree.");

String[] tokens = value.split(" ");//if you input name followed by space followed by degree, this splits the input by the space between them
System.out.println(tokens[0]);//shows the name
System.out.println(tokens[1]);//shows the degree

これで、を使用tokens[0]して名前をリストに追加できます。

于 2013-03-18T20:16:39.257 に答える