How do I handle multiple inputs using java.util.Scanner? - java

I am new to Java and when I wrote following code I faced this problem. I want to get a square matrix from user but first I get the number of columns and then I get the matrix and to handle this question I wrote this code:
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);
}
}
}
}
I want to handle this input:
3
1 0 1
1 0 1
1 1 0
However, I type in:
3<enter>
1 0 1<enter>
Program exits just after the first entered row. How do I fix it?

If you are creating a matrix like used in a graph to show connections and you know how many there will be why not try a 2d array.
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++
}
}
}
}

This should help :
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) + " ");
}
}
}
}

1 Remember to import some of the features when needed; java.util.Scanner must be explicitly imported.
2 Messing with (Array)List is not needed here; use a regular array.
3 Scanner.nextInt() reads the whole line and parses an int at the beginning. Here you need to split the input by spaces.
Final code:
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();
}
}
}

Related

Matrix in methos

If I have a partially filled 2D matrix from user input, how can I fill it in some other void method to get spiral matrix:
Here is my code: However, when I run it the dimensions of matrix still remain 1000X1000. How can I fix this problem? I need to have only two methods - fillSpiral and main. The program should get any square matrix from user then change its values in a way it becomes a spiral matrix.
import java.util.Scanner;
public class Spiral {
public static void fillSpiral(int matrix[][]) {
int row1 = 0, row2 = matrix.length, col1 = 0, col2 = matrix[0].length;
int num = 1;
while (num <= matrix.length) {
for (int col = col2-1; col >= col1; col--){
matrix[row2-1][col] = num;
num++;
}
for (int row = row2-2; row >= row1; row--) {
matrix[row][col1] = num;
num++;
}
for (int col = col1+1; col < col2; col++) {
matrix[row1][col] = num;
num++;
}
for (int row = row1+1; row < row2-1; row++) {
matrix[row][col2-1] = num;
num++;
}
row1++;
row2--;
col1++;
col2--;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
public static void main(String args[]) {
int n = 0;
int[][] matrixOutput = new int[1000][1000];
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<matrixOutput.length; i++) {
for (int j=0; j<matrixOutput[0].length; j++){
while (keyboard.hasNextInt()) {
matrixOutput[i][j] = keyboard.nextInt();
n++;
}
}
}
fillSpiral(matrixOutput);
}
}
example
Input
1 2 3
4 5 6
7 8 9
Output
5 6 7
4 9 8
3 2 1
Since the algorithm for an spiral matrix is not new i assume your only problem is to read a matrix of an fixed size. Then addressing only your main method use this
//i preferr buffered reader over scanner
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)))
{
ArrayList<String> rows=new ArrayList();
String line=null;
do
{
//example 1,2,3,4,5
System.out.println("Enter an row for this matrix all elements , seperated or an empty string to end input");
line=reader.readLine().trim();
if(!(line.isEmpty() || line.isBlank())){rows.add(line);}
else{line=null;}
}
while(line!=null);
//i assume a square matrix so rows=columns
int n=rows.size();
int[][] matrix=new int[n][n];
for(int i=0;i<n;i++)
{
//split at comma to get columns
String[] columns=rows.get(i).split(",");
//assign each column to the ith row
for(int j=0;j<n;j++){matrix[i][j]=Integer.parseInt(columns[j]);}
}
fillSpiral(matrix);
}

The code below reads from a text argument and displays an m x n matrice, I want to pass another text argument and compare it with the first 1

// here is a sample text file below board.txt
/* 4 4
x t x .
. . s .
x . . .
moves.txt lru
l for left, r for right u for up and d for down.
The first text file argument is a board game file on which s represents a start position and t the target.
and the second text file argument is a moves text file. I want to pass the second argument so that I can make those moves across the board file.
*/
public class VGame {
public static void main(String[] args) {
int m = StdIn.readInt();
int n = StdIn.readInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < board1.length; i++) {
// the condition becomes false then gives access back to the outer for loop
for (int j = 0; j < board1[i].length; j++) {
board1[i][j] = StdIn.readString(); //reading from a text files
}
}
// now let's print a two dimensional array in Java for
/*for (char[] a : board1)
{
for (char i : a)
{
System.out.print(i + " ");
} System.out.println("\n");
} */
StdOut.println(m + " " + n);
for (int i = 0; i < board1.length; i++)
{
for (int j = 0; j < board1[i].length; j++)
{
System.out.print(" "+ board1[i][j]);
}
System.out.println();
}
// printing 2D array using Arrays.deepToString() method
//System.out.println("another way to print 2D arrays");
//System.out.println(Arrays.deepToString(board1));
StdOut.println(args[0]);
}
}
this should read the indexes as Integer and then the String line-by-line.
public class Main {
public static void main(String[] args) {
int m = 0;
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("input m: ");
m = s.nextInt();
System.out.print("input n: ");
n = s.nextInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print("input string: ");
board1[i][j] = s.nextLine();
}
}
s.close();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.println(board1[i][j]);
}
}
}
}

How do I print the 0s and 1s automatically in the 2D array and count the 1s and 0s in it?

So far, my code is this one:
import java.util.Scanner;
public class PG1 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
//declaration,creation, initialization
double [][] matrix = new double [i][j];
//print element in row i
for (i = 0; i < matrix.length;i++){
//print element j in row i
for (j = 0; j < matrix[i].length; j++) {
System.out.print("The matrix is: " + matrix[i][j]);
}
System.out.println();
}
}
}
So basically, I want to print the 0s and 1s according to the user's input or row and column of the matrix. Your help will be much appreciated.
output:
Enter the length of the matrix: 4
The matrix:
0 1 1 1
0 0 0 0
0 1 0 0
1 1 1 1
All 0s on row 1
All 1s on row 3
No same numbers on a column
No same numbers on the diagona
you can achive like this:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0){
count0s++
System.out.print("The matrix is: " + matrix[i][j]);
}
else if(matrix[i][j] == 1){
count1s++
System.out.print("The matrix is: " + matrix[i][j]);
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}
}
If you dont want to print 0s and 1s :
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0)
count0s++
else if(matrix[i][j] == 1)
count1s++
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}

Arrays FindMax What am I missing?

I have a project that says,"Write a program to read a list of integer numbers and print the largest number among them.
For example: if user enters: 9 11 15 3 7 9
it prints out 15.
What am I missing? Here is the output
import java.util.Scanner;
public class FindMax {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the list");
int size = scan.nextInt();
int[] list = new int[size];
int i;
for (i = 0; i < size; i++) {
list[i] = scan.nextInt();
}
int max = list[0];
for (i = 0; i > size; i++) {
if (list[i] > max)
max = list[i];
}
System.out.println(max);
}
}
The problem is in your second loop:
for ( i=0; i > size; i++)
It should be while i is SMALLER than size:
for ( i=0; i < size; i++)
Otherwise, it skips that loop and returns the default maximum which you set at list[0]

Java Matrix using Arrays

I'm struggling to find an answer to the problem below. User inputs rows and columns. Example below is given for 4 x 4 matrix.
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
I cannot find how to relate the numbers when printing the array. The only obvious relation is how it goes downwards and upwards. From my perspective looks really hard. I'm just a beginner.
Not quite sure if there is any point to post the code, but it's just the basic lines:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
array[i][j]=...(stuck at the beginning);
}
Probably I'd need to use several loops , not only the above-mentioned or probably it is totally wrong ...
Thank you in advance!
I think this should do it.
int counter = 0;
boolean top_to_bottom=true;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
if(top_to_bottom)
array[i][j]=counter;
else
array[rows-1-i][j]=counter;
}
if(top_to_bottom)
top_to_bottom=false;
else top_to_bottom=true;
}
It serves the purpose
import java.util.*;
public class Seq
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
if(j%2==0)
{
for (int i = 0; i < rows; i++)
{
counter=counter+1;
array[i][j]=counter;
}
}
else
{
for (int i = rows-1; i >=0; i--)
{
counter=counter+1;
array[i][j]=counter;
}
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}

Categories