使用用户输入使用prompt-Java填充2D String数组

时间:2016-04-14 08:34:04

标签: java arrays

这是我的代码,我的问题是在输入rowNum和colNum的值后,它会显示“请输入一个值”提示两次并填充第一部分w /它看起来像是一个空格。帮助将不胜感激!

import java.util.*;

public class Lab11 {
    public static void main(String[] args){

        // A scanner object for requesting input from the user
        Scanner scan = new Scanner(System.in);
        // An integer for the number of rows.
        int rowNum;
        // An integer for the number of columns.
        int colNum;
        //a string search for the string to search for
        String search;

     // Print this message "Enter the number of rows in the array" //
        System.out.print("Enter the number of rows in the array" );
        rowNum = scan.nextInt();
     // Print this message "Enter the number of columns in the array //
        System.out.print("Enter the number of columns in the array");
        colNum = scan.nextInt();
     // Use the scanner to store the values entered by the user
     // in the integers declared above.

     // Declare a 2D String array using the number of rows and columns previously entered by the user
     String[][] stringArray = new String[rowNum][colNum];

     for (int i = 0; i < stringArray.length; i++){
         for (int j = 0; j < stringArray[i].length; j++){
             System.out.println("Please enter a value");
             stringArray[i][j] = scan.nextLine();
         }
     }

     for (int ii = 0; ii < stringArray.length; ii++){
           for (int jj = 0; jj < stringArray[ii].length; jj++){
               System.out.print(stringArray[ii][jj]+" ");
           }
           System.out.println();
     }

     System.out.println("Please enter the string you are searching for");
     search = scan.nextLine();
     for (int iii = 0; iii < stringArray.length; iii++){
         for (int jjj = 0; jjj < stringArray[iii].length; jjj++){
             if(stringArray[iii][jjj].equals(search)){
                 System.out.println("Element found at position ("+iii+","+jjj+")");
             }
         }
     }



    }

}

1 个答案:

答案 0 :(得分:0)

这是因为scan.nextInt();方法不消耗输入的最后一个换行符,因此在下次调用scan.nextLine时会消耗换行符,所以你需要这样使用{{1这里我们正在进行类型转换并使用Integer.parseInt(scan.nextLine());方法而不是nextLine()。和扫描是扫描仪类的对象。

所以,我修改了你的代码,它工作正常,

nextInt()