首页 > 解决方案 > 在同一行 JAVA 上获取各种整数输入

问题描述

我想integer在同一行接受各种输入,比如说 2。实际上我想以矩阵的形式输入,因为输入值将以矩阵的形式存储。

问题是我每行只能接受一个输入,然后它会转到下一行以接受下一个输入。我认为它Scanner.nextInt()会导致光标移动到下一行,因为我必须在每次输入后按回车键。

代码:

import java.util.Scanner;
public class Matrix
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        boolean flag = false;
        int row = 2 , col =2;
        int[][] array = new int[row][col];
        do
        {
            System.out.printf("\n>>>>> Enter values for Matrix <<<<<\n");
            try
            {
                for (int i = 0; i < row; i++) 
                {
                    System.out.print("\n[  ");
                    for (int j = 0; j < col; j++) 
                    {
                        array[i][j] = input.nextInt();
                        System.out.print("   ");
                    }
                    System.out.print("  ]\n");
                }
                flag = true;
            }
            catch(Exception e)
            {
                System.out.println("Invalid Input. Try Again.");
                String flush = input.next();
                flag = false;
            }
        }while(!flag);      
    }
}

输出:

结果

期望的输出:

[ 2 3 ]

[ 8 4 ]

我已经在互联网上搜索了这个问题,但是每个人都在每行输入一个输入,但我希望它以矩阵样式输入。

标签: javamatrixinputformattingjava.util.scanner

解决方案


您可以将输入行读取为由空格分隔的数字字符串,然后将其拆分

for (int i = 0; i < row; i++) 
{
    System.out.print("\n[  ");
    String matrixRow = input.next();
    String[] numbers = matrixRow.split(" ");
    for (int j = 0; j < col; j++) 
    {
         array[i][j] = Integer.parseInt(numbers[j]);
     }
     System.out.print("  ]\n");
}

推荐阅读