[英]How do I handle multiple inputs using java.util.Scanner?
我是Java的新手,编写以下代码时遇到了这个问题。 我想从用户那里得到一个方矩阵,但是首先我得到了列数,然后我得到了矩阵并处理了这个问题,我编写了这段代码:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++)
{
matrix.add(new ArrayList<Integer>());
for (int j = 0; j < n; j++)
{
n = input.nextInt();
matrix.get(i).add(n);
}
}
}
}
我要处理此输入:
3
1 0 1
1 0 1
1 1 0
但是,我输入:
3<enter>
1 0 1<enter>
程序将在第一行输入之后退出。 我如何解决它?
这应该有帮助:
import java.util.ArrayList;
import java.util.Scanner;
public class A {
public static void main(String []args) {
int n ;
Scanner input = new Scanner(System.in);
System.out.println("Columns : ");
n = input.nextInt();
ArrayList<List<Integer>> matrix = new ArrayList<List<Integer>>();
for ( int i = 0 ; i < n ; i++ )
{
matrix.add(new List<Integer>());
for ( int j = 0 ; j < n ; j++ )
{
int t = input.nextInt();
matrix.get(i).add(t);
}
}
/* This is to check the contents of the data structure */
for ( int j = 0 ; j < n ; j ++)
{
System.out.println();
for ( int k = 0 ; k < n ; k ++)
{
System.out.print(matrix.get(j).getElement(k) + " ");
}
}
}
}
如果您要创建一个像在图表中使用的矩阵来显示连接,并且知道会有多少个不尝试2d数组的原因。
public static void main(String []args) {
int n,m ;
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[][] matrix = new int[n][n];
for ( int i = 0 ; i < n ; i++ )
{ int j= 0;
while(input.hasNext() && j< matrix[].lenght)
{
m = input.nextInt();
matrix[i][j] = m;
j++
}
}
}
}
1记住在需要时导入一些功能; 必须显式导入java.util.Scanner
。
2这里不需要使用(Array)List
进行处理; 使用常规数组。
3 Scanner.nextInt()
读取整行并在开始处解析一个int
。 在这里,您需要按空格分隔输入。
最终代码:
import java.util.Scanner; // note 1
import java.util.Arrays; // small utility
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt(); // load the size
int[][] matrix = new int[size][size]; // create a new array; note 2
for(int row = 0; row < size; ++row) {
String[] input = sc.nextLine().split(" "); // read a row
input = Arrays.copyOf(input, size); // pad/truncate the array
int[] processed = new int[size]; // for storing a row
for(int entry = 0; entry < size; ++entry)
processed[entry] = Integer.parseInt(input[entry]); // parse integers; note 3
matrix[row] = processed; // set the row
}
// for testing purposes:
for(int row = 0; row < size; ++row) {
for(int col = 0; col < size; ++col)
System.out.print(matrix[row][col] + " ");
System.out.println();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.