java - 在同一行 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 ]
我已经在互联网上搜索了这个问题,但是每个人都在每行输入一个输入,但我希望它以矩阵样式输入。
解决方案
您可以将输入行读取为由空格分隔的数字字符串,然后将其拆分
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");
}
推荐阅读
- android - 获取 Flow 发出的最后一项并且不接收更新
- ruby-on-rails - 从查询后生成的模型中删除属性
- sql - 访问查询:使用用户输入在sql中选择要查询的列
- graphql - 无法在 GraphQL 中实现联合
- xpath - DOM4J XPath 2.0
- sql - 在 SQL Server 2005 中启用 CDC 不起作用?
- google-apps-script - 如何搜索包含空格的文件名,以便消除空格
- reactjs - React js 上传大文件(视频或pdf)
- swiftui - 如何使用 DateFormatter 显示昨天、今天和明天
- python - Django 使用 Piexif 更新 InMemoryUploadedFile