2016-11-20 8 views
1

名前(文字列)の2つの配列を持つJavaプログラムを作成しようとしています。もう1つは年齢(整数)を表し、プログラムは繰り返して最大10の名前と年齢を求めますすべての配列項目、それぞれの最大および最小の年齢を表示するか、途中で「完了」または「完了」と入力しない限り表示します。配列を使ったJavaの繰り返し

私は次のコードを持っていますが、周りをループしてユーザーに名前と年齢x10を尋ねるのに苦労します。

提案がありますか?

ありがとうございます。

import java.util.Scanner; 
public class AgeName { 
    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 

     int numTried = 1; 
     int ageTried = 1; 
     boolean stop = false; 
     String name = ""; 

     String[] num = new String[10]; 
     int[] age = new int[10]; 

     while(numTried <= 10 && ageTried <=10 && !stop){ 
      System.out.print("Enter name " + numTried + ": "); 
      name = input.nextLine(); 

      System.out.print("Now enter age of " + name + ": "); 
      int userAge = input.nextInt(); 

      if(name.toUpperCase().equals("DONE")){ 
       stop = true; 
      }else{ 
       num[numTried - 1] = name; 
       age[ageTried -1] = userAge; 
      } 

      numTried ++; 
      ageTried ++; 
     } 

     for(String output : num){ 
      if(!(output == null)){ 
       System.out.print(output + ","); 
      } 
     } 

     input.close(); 
    } 
} 
+0

あなたはそれを試しましたか? – ItamarG3

答えて

1

あなたはMap<String,Integer>を使用することができます。

HashMap<String, Integer> map = new HashMap<String, Integer>(); 
String[] num = new String[10]; 
for (int i = 0; i < 10; i++) { 
    System.out.print("Enter name " + numTried + ": "); 
    name = input.nextLine(); 

    System.out.print("Now enter age of " + name + ": "); 
    int userAge = input.nextInt(); 
    num[i] = name; 
    map.put(name, userAge); 
} 

for (String output : num) { 
    if (!(output == null)) { 
     System.out.print(output + ","+ map.get(output)); 
    } 
} 

Mapその名の通り、あなたが別のオブジェクト型をマップすることができます。 .put()メソッドは、Stringintegerのペアを含むレコードを追加し、その文字列をintにマップします。
文字列はユニークです!

0

ユーザーが完了しているかどうかを尋ねる必要があります。たとえば、文字列変数をanswer = "NO"に設定し、完了したら繰り返しの最後にユーザーに尋ねることができます。これを試すと、反復ブロック条件でstop変数をanswerに置き換えることを忘れないでください。

System.out.println("Are you done: Choose -> YES or NO?"); 
answer = input.nextLine(); 
if (answer == "YES") 
    break; 
関連する問題