2014-04-06 2 views
1
int number = keyboard.nextInt(); 
String [][] myArray = new String[number][1] 
for (int i = 0; i < x; i++) 
{ 
    System.out.println("Enter food name: "); 
    myArray[i][0] = keyboard.nextLine(); 

    for (int j = 0; j < 1; j++) 
    { 
    System.out.println("Enter the type of this food: "); 
    myArray[i][j] = keyboard.nextLine(); 
    } 
} 

다음은 내가 요청하려고하는 코드입니다. 이 프로그램을 실행할 때 출력물을 출력하고 싶습니다.배열에 문제가 있습니까 (사용자 다중 입력 관련)?

Enter food name: 
(where user type his or her input) 
Enter the type of this food: 
(where user type his or her input) 

(My problem is it prints out this instead for the first loop:) 
Enter food name: 
Enter the type of this food: 
(where user type his or her input) 

음식물을 넣을 방법이 없습니다. 첫 번째 루프가 끝나면 프로그램은 원하는 출력으로 정상으로 돌아 오지만 첫 번째 루프가 "입력 식품 이름 :"에 대한 사용자 입력을 가져 오도록 코드를 어떻게 변경합니까?

미리 감사드립니다.

편집 : 사전에 그 질문을 보지 못해서 미안하지만 for 루프에 관한 것이 아니기 때문에 다음 입력 전에 빈 문자열을 입력하면 루프가 작동하지 않습니다. 이 문제가 수정 되었습니까?

편집 : 작동하도록했습니다. 모두에게 감사드립니다.

+1

[이용 nextInt 후 꽵 스키핑() (가능 중복 http://stackoverflow.com/questions/13102045/skipping-nextline-after -use-nextint) – cheseaux

+0

아, 그 일찍 보지 못해 죄송합니다. 루프에 대한 수정이 있습니까? 그 질문에 대한 대답과 같은 방법입니까? – user3503794

+0

'int 뒤에'keyboard.nextLine();을 씁니다. number = keyboard.nextInt();'line and you ' 모두 갖추어져있어. –

답변

0

아래와 같은 코드를 시도해 볼 수 있습니다 (사용자가 입력 할 항목의 수를 알 필요없이 입력이 끝날 때까지 정보를 입력 할 수 있습니다.) 또한 입력을 처리 할 수있는 방법이 만들어집니다 만약 향상시킬 수 있도록 .. 쉽게 조정 방법.

import java.io.ObjectInputStream.GetField; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class Foodarray { 

private static String[][] foodInformation; 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    Scanner keyboard = new Scanner(System.in); 
    foodInformation = getFoodInformation(keyboard); 

} 

private static String[][] getFoodInformation(Scanner inputDevice) { 
    String[][] result = null; 
    boolean isStoping = false; 
    ArrayList<String> holdName = new ArrayList<String>(); 
    ArrayList<String> holdType = new ArrayList<String>(); 

    while (!isStoping) { 
     System.out.println("Enter food name (or end to exit): "); 
     String foodName = inputDevice.nextLine().trim(); 
     isStoping = "end".equalsIgnoreCase(foodName); 
     if (!isStoping) { 
      System.out.println("Enter food type"); 
      String foodType = inputDevice.nextLine().trim(); 
      holdName.add(foodName); 
      holdType.add(foodType); 
     } 
    } 
    int foodCount = holdName.size(); 
    if (foodCount>0) { 
     result = new String[foodCount][foodCount]; 
     for (int i=0; i < foodCount; i++) { 
      result[i][0] = holdName.get(i); 
      result[i][1] = holdType.get(i); 
     } 
    } 

    return result; 

} 

} 
+0

입력 해 주셔서 감사합니다. 나는 그것을 확실히 체크 할 것이다. – user3503794

관련 문제