我想在同一行上获取各种整数
输入,比如说2。实际上我想以矩阵的形式输入,因为输入值将存储在矩阵的一种形式。
问题是我每行只能接受一个输入,并且它会转到下一行以接受下一个输入。我认为它的 Scanner.nextInt() 会导致光标到达下一行,因为我必须在给出每个输入后按 Enter 键。
代码:
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 ]
我在互联网上搜索过这个问题,但每个人都每行接受一个输入,但我希望它以矩阵样式输入。
最佳答案
您可以将输入行读取为由空格分隔的数字字符串,然后将其拆分
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");
}
关于java - 在同一行 JAVA 中获取各种整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325718/