reading in values to insert in a 2d array - java

I am working on an assignment in which I need to read in sample input from a file and insert it into a 2D array. Here is an example of input:
5 6
1 3 4 B 4 3
0 3 5 0 0 9
0 5 3 5 0 2
4 3 4 0 0 4
0 2 9 S 2 1
The 5 and 6 are the dimensions of the array. The user must be able to input many arrays like this one at once, the program ends when the user inputs -1. This is the code I have so far that doesn't seem to be working as it should(I print out the array to make sure the code works):
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();
sc.useDelimiter(" ");
String[][] map = new String[arHeight][arWidth];
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();
}//end inner for
}//end outter for
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}//end outter for
}
The assignment states that I cannot use recursion and that I must use 2D arrays. I have looked at other questions but still can't seem to figure it out.
Thanks for the help!!

you read the whole line i*j times
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();
also you keep al the data in a string array and I don't know why. Here is the solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();
int[][] map = new int[arHeight][arWidth];
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextInt();
}//end inner for
}//end outter for
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}
}
Then try to use
char[][] map = new char[arHeight][arWidth];
and in the for loop:
if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0);
This way you should read all the chars which are not " ".

Related

How can I print just specific elements of a Java 2D array?

Below is the code I'm messing with, pretty basic. I was looking for a way to print only specific elements of the array. For example, if I wanted to print only the element at index 1 of array[i], as well as the element at index 1 of array[j] when its value is 1. See below for the output I'm looking for.
Expected output :
1 3 5
4
7 8 9
Code:
public class multiDimensional {
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
System.out.print(arr[i][j]+" ");
//System.out.println();
}
System.out.println();
}
}
}
Actual output :
1 3 5
2 4 6
7 8 9
You can produce your expected output by using an if statement to decide when to write a value:
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
if (i == 0 // in the first row
|| i == 2 // in the last row
|| j == 1) { // in the middle column of the middle row
System.out.print(arr[i][j]+" ");
} else {
System.out.print(" "); // this is here to keep the spacing right
}
//System.out.println();
}
System.out.println();
}
}
Note: There are many other ways of coding this, however the approach I am showing is merely to demonstrate how the if statement works.

I am only able to print up to "red: 1" only, after which my program ends due to usage of break statement

Please see this code:
import java.util.Scanner;
public class Array
{
public static void main(String args[])
{
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++)
{
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
Scanner scan2=new Scanner(System.in);
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextLine();
}
OUTER:
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":");
break OUTER;
}
INNER:
for (int l = 0; l < numbers.length; l++)
{
System.out.println(numbers[ l ]);
break INNER;
}
}
}
I am a newbie, learning Array as of now, in Java. I want to print the outcome of the code above as follows:
Enter 5 numbers:
//Say:
RED
GREEN
BLUE
PINK
YELLOW
Enter 5 numbers:
1
2
3
4
5
//Output of the code should be:
RED: 1
GREEN: 2
BLUE: 3
PINK: 4
YELLOW: 5
How can I print the array? I am only able to print up to "RED: 1" only, after which my program ends due to break statement.
Your last for does not a have any purpose. Just try :
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++){
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++) {
numbers[j]=scan.nextLine();
}
for (int k = 0; k < names.length; k++){
System.out.println(names[ k ] + ":"+ numbers[k]);
}
}
}
ANd it's stop at the first because you break your for
scan.nextLine() reads the whole line of input that is it reads until you don't enter \n new line charachter, so use nextInt() instead of that. Also each System.out.println() is used to print a whole line so only one loop can be used. If names and numbers have same length. And change numbers[] from String to int, that would be more type safe.
int numbers[] = new int[5];
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextInt();
}
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":" + numbers[k]);
}
Since the number of elements be it color or numericals that you're trying to get from the user is fixed here i.e 5, why complicate things? Use a single for loop to print all the contents of both the arrays:
for(int k=0;k<names.length;k++){
System.out.println(names[k] + ":"+numbers[k]);
}

Printing a Square Matrix and Transposing it with Java

I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.

Put a 2-d array in another 2-d array java

I am having trouble figuring out how to put one 2-D array into another one.
public class MazeAnalyze{
public static void main(String[]args){
Scanner kbd = new Scanner(System.in);
String str = "";
System.out.println("Enter dimensions");
int n = kbd.nextInt();
char [][] mazeValue = new char[n][n];
char[][] newMaze = new char[n+2][n+2];
String [] input= new String [n];
int [][] totalOpen = new int [n][n];
char X= 88;
System.out.println("Enter the maze");
for(int i =0; i <input.length; i++){
input[i] = kbd.next().toUpperCase();
}
for(int x=0; x< input.length;x++){
mazeValue[x]= input[x].toCharArray();
}
System.out.println("The maze array contains:");
for(int i=0; i<mazeValue.length; i++){
for(int j=0; j<mazeValue[i].length;j++){
System.out.print(mazeValue[i][j]);
}//end of second loop
System.out.println();
}//end of first loop
System.out.println("The maze with the Xs are");
for(int i=0; i<newMaze.length; i++){
for(int j=0; j<newMaze[i].length;j++){
newMaze[i][j]= 'X';
}//end of second loop
}//end of first loop
for(int i=0; i<newMaze.length; i++){
for(int j=0; j<newMaze[i].length;j++){
System.out.print(newMaze[i][j]);
}
System.out.println();
}
for(int x=0; x<n-2; x++){
for(int i=0; i<mazeValue.length; i++){
for(int j=0; j<mazeValue[i].length;j++){
newMaze[i+1][j+1]= mazeValue[i][j];
}
}
}//end of main for loop
This is my output:
Enter dimensions
3
Enter the maze
xox
xoo
ooo
The maze array contains:
XOX
XOO
OOO
The maze with the Xs are
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
The maze with the border is
XOX
XOO
OOO
What I want is:
My maze array surrounded by X's like a border. Any suggestions?
Simplest way in your case seems to be using string concat and add "X" and the beginning and end of each line, and in addition add 2 lines to input - one at the start and one at the end, all containing only "XXX...X".
Note: It might be easier to use an ArrayList<String> or LinkedList<String> for input rather than String[] - adding elements at the start and end would be easier.

Printing a 2d array in Java like a table [duplicate]

This question already has answers here:
How to print Two-Dimensional Array like table
(16 answers)
Closed 9 years ago.
I'd like to print an inputed 2-dimensional array like a table
i.e if for some reason they put in all 1s...
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Just like so above but in the console on Java eclipse, no fancy buttons and GUI's but in the console, here is what I have....
import java.util.Scanner;
public class Client {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i=0; i < table.length; i++) {
for (int j=0; j < table.length; j++) {
System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println(table);
}
}
And this is what I get when I input everything and the console terminates:
Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1
[[I#3fa1732d
Consider using java.util.Arrays.
There is a method in there called deepToString. This will work great here.
System.out.println(Arrays.deepToString(table));
Relevant here: Simplest way to print an array in Java
You need to print out the array separately from entering the number. So you can do something like this:
public class PrintArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
// System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
}
//System.out.println();
}
// System.out.println(table);
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
You'll have loop back through those arrays to print out the contents. an array's toString() just prints the reference value.
System.out.print(table) calls a method in array class that prints out the identifier of the vairable. you need to either create a for loop that will print out each element like System.out.print(table[i][j]) or use the Arrays class and say Arrays.toString(table);
Try copying this simple for loop to printing a 4x4 table:
Scanner input = new Scanner();
int numArray [] [] = new int [4] [4];
for ( int c = 0; c < 4; c++ ) {
for (int d = 0; d < 4; d++) {
System.out.print("Enter number : ");
nunArray [c][d] = input.nextInt();
}
}
for (int a = 1; a<5;a++) {
for (int b = 1; b <5;b++) {
System.out.print(numArray [a][b]+" ");
}
System.out.println();
}

Categories