I am trying to get the String right after the position i input, but it is not working and i can not identify why.
This is my code.
import java.util.*;
public class LabTest1_Mardi {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
String myArray [][] = { {"a","b"}, {"c","d"}, {"e","f"}, {"g","h"}};
//Getting row and cols
int rows = myArray.length;
int cols = myArray[0].length;
System.out.println("Rows = "+rows+" Cols = "+cols);
for (int x=0;x<rows;x++){
for (int y =0;y<cols;y++){
System.out.println("array "+x+" " + y + " : = "+myArray[x][y]);
}
}
System.out.println("Enter Possition row : ");
int posR = input.nextInt();
System.out.println("Enter Possition col : ");
int posC = input.nextInt();
System.out.println(myArray[posR+1][posC+1]);
input.close();
}
}
Which position are you trying to get? For example, if you enter in 0,0 (a) do you want b (0,1) or c (1,0)? Right now it should return d (1,1) because both row and column are incremented.
Image your 2D array looks like this,
0 , 1
0: a , b
1: c , d
2: e , f
3: g , h
Right now you're shifting both row and column, make sure that's exactly what you want to do. Also you'll get an error if the user enters a 1 as their input values.
Related
I am still new to Java and have been working with 2D arrays recently. What I am trying to do is make a simple 2D grid array of a Chessboard that has the arrays from a1 all the way to h8. The first thing I tried to do is convert the array [8][8] so that the first 8 was characters and the second 8 was integers. What I am currently trying to do is prompt the user and ask them which coordinate they would like to choose (from a1 all the way to h8). When they choose one of the coordinates, I would like them to enter a string (which in the future will be my chess pieces) that will be stored on the board, so that, when I use another class to print these strings, it'll give me an output like "a5 - Lemon (As im not checking to see if the chess piece is a valid piece yet) or "h2 - Queen".
So, to clarify, the program asks the user "Please enter a coordinate (e.g. a5)". "Now, Please enter a piece to be placed on that coordinate" Which then gets stored in that coordinate. When the user types, for example, "Done" I would like all the coordinates that have pieces on them to be revealed as well as what piece was put on them.
Code:
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
int[][] grid = new int [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int col = (int)(input.charAt(0) - 'a');
int row = (int)(input.charAt(1) - '0');
}
}
}
I have used a while loop to continuously prompt the user until they give a correct coordinate, but Im not sure how to prompt the user to enter a piece that gets stored in that coordinate?
Any help would be appreciated!
First of all, in order to store the piece name with the coordinates, you will need a 2D array of strings instead of integers.
After changing that, you take the user input again and then save the coordinates with the piece and save it in the 2d array at said column and row.
Also, the row is retrieved from the character (a-b-c-etc..) and the column from the number and not the way around.
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
I am trying to read elements of a 2-d 3x3 matrix using a scanner.
The input would look something like this:
3
11 2 4
4 5 6
10 8 -12
I am current geting the error:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();
List<List<Integer>> array = new ArrayList<>();
for (int i = 0; i < a; i++) {
String number = scan.nextLine();
String[] arrRowItems1 = number.split(" ");
List<Integer> list = new ArrayList<>();
for (int j = 0; j < a; j++) {
int arrItem = Integer.parseInt(arrRowItems1[j]);
list.add(arrItem);
}
array.add(list);
}
scan.close();
How do I go about doing this problem, so that a the end a 2d 3x3 matrix array is constructed according to user input? Thank You.
Do the following:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine
Your program works just fine the way it was written as long as you make the above change. However, I recommend you split on "\\s+" to allow any number of spaces between the numbers.
You could read the input line-by-line as a string, check it for validity, parse it and fill it in an int[][]-Matrix.
This way, the program keeps asking for input until it got three valid lines of numbers:
Scanner scan = new Scanner(System.in);
int dim = 3; //dimensions of the matrix
int line = 1; //we start with line 1
int[][] matrix = new int[dim][dim]; //the target matrix
while(line <= dim) {
System.out.print("Enter values for line " + line + ": "); //ask for line
String in = scan.nextLine(); //prompt for line
String[] nums; //declare line numbers array variable
//check input for validity
if (!in.matches("[\\-\\d\\s]+")
| (nums = in.trim().split("\\s")).length != dim) {
System.out.println("Invalid input!");
continue;
}
//fill line data into target matrix
for (int i = 0; i < nums.length; i++) {
matrix[line - 1][i] = Integer.parseInt(nums[i]);
}
line++; //next line
}
scan.close(); //close scanner (!)
//test output
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
The last for-loop is only for printing the result, just to check if it works:
Enter values for line 1: 11 2 4
Enter values for line 2: 4 5 6
Enter values for line 3: 10 8 -12
[11, 2, 4]
[4, 5, 6]
[10, 8, -12]
BTW by changing the value for dim (dimension) you could even get a 5x5 or whatever matrix!
I hope this helped!
So I have an assignment where I take in doubles from the user in the console and then store those doubles in an array. These doubles will actually be coordinates which I will use later on.
The program should be able to take an unknown amount of doubles from the user. The problem I am having is allowing the array size to grow dynamically. We CANNOT use arrayList or any java library collection classes. Here is what i have so far:
import java.util.Scanner;
public class testMain{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
boolean debug = true;
//Two array's where i'll store the coordinates
double[] coord1 = new double[3];
double[] coord2 = new double[3];
//Array for user commands
String[] commands = { "random", "exit", "help"};
for(int i = 0; i < coord1.length; i++){
System.out.println("Enter Coordinates: ");
double index = userInput.nextDouble();
//If more doubles needed for array we want to resize array
if(coord1[i] >= coord1.length){
for(int j = 0; j < 10; j++){
coord1[j] = j + 10;
}
double newItems[] = new double[20];
System.arraycopy(coord1, 0, newItems, 0 ,10);
coord1 = newItems;
}
coord1[i] = index;
}
if(debug == true){
printArray(coord1);
}
}
public static void printArray(double arr[]){
double n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
I can't seem to figure out how to recognize when the reaching the end of coord1 to execute code to increase the size and continue looping for more doubles.
Later on when the user is done an empty entry from console should exit loop and display the array.
Your problem is that you use a for loop, which is only looping over every element of your array. So, it will never give the user a chance to enter more elements than are in the array. Use a while loop so that instead of looping once for every element, you can loop until the user enters "exit".
Here is a slight modification of your code that should work:
Scanner userInput = new Scanner(System.in);
//Two array's where i'll store the coordinates
double[] coord1 = new double[3];
double[] coord2 = new double[3];
//Array for user commands
String[] commands = { "random", "exit", "help"};
System.out.println("Enter Coordinates: ");
String input = userInput.nextLine();
int arrayIndex = 0;
while (!input.equals("exit")) {
//convert input to a double
System.out.println("Enter Coordinates: ");
double userDouble = Double.parseDouble(input);
//handle case where array needs to be resized
if (arrayIndex >= coord1.length) {
double[] newCoord1 = new double[coord1.length * 2];
for (int copyIndex = 0; copyIndex < coord1.length; copyIndex++) {
newCoord1[copyIndex] = coord1[copyIndex];
}
coord1 = newCoord1;
}
//store the value
coord1[arrayIndex] = userDouble;
arrayIndex = arrayIndex + 1;
//take new input
input = userInput.nextLine();
}
Keep in mind that this doubles the array size when a resize is needed. That means that if the array size doubles to 6 and the user only enters 5 values, you will have a couple of empty values (zeros) at the end of your array. If that is a problem you can modify it.
You can use a while to loop until the command "exit" is typed by the user. here is an example of dynamically adding elements to the array before each item is added to the array.
String[] number;
String userInput = "";
String[] commands = { "random", "exit", "help"};
double[] coord1 = new double[0];
double[] coord2 = new double[0];
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter Coordinates (ex 1,3)\n");
userInput = scan.nextLine();
if(!userInput.equals(commands[1]))
{
number = userInput.split(",");
if(number.length != 2 || !number[0].matches("\\d+") || !number[1].matches("\\d+"))
{
System.out.println("Error: Invalid Input! Try again");
}
else
{
//our index to place our numbers will be the current length of our array
int index = coord1.length;
double[] temp = new double[coord1.length + 1];
//copy the content to the same array but just 1 size bigger
System.arraycopy(coord1, 0, temp, 0, coord1.length);
coord1 = temp;
temp = new double[coord2.length + 1];
System.arraycopy(coord2, 0, temp, 0, coord2.length);
coord2 = temp;
//now use our index to place the numbers in the correct locations
coord1[index] = Double.parseDouble(number[0]);
coord2[index] = Double.parseDouble(number[1]);
}
}
} while (!userInput.equals(commands[1]));
for(int i = 0; i < coord1.length; i++)
{
System.out.println(i + " - X: " + coord1[i] + " Y: " + coord2[i]);
}
Note I use comma seperated values to make the user's life and my life easier, allowing them to enter the coordinates at the same time.
Example output
Enter Coordinates (ex 1,3)
1,5
Enter Coordinates (ex 1,3)
4,7
Enter Coordinates (ex 1,3)
8,9
Enter Coordinates (ex 1,3)
gffd
Error: Invalid Input! Try again
Enter Coordinates (ex 1,3)
3 6
Error: Invalid Input! Try again
Enter Coordinates (ex 1,3)
0,0
Enter Coordinates (ex 1,3)
exit
0 - X: 1.0 Y: 5.0
1 - X: 4.0 Y: 7.0
2 - X: 8.0 Y: 9.0
3 - X: 0.0 Y: 0.0
I am trying to print arrays before and after they are filled with user given inputs. Therefore, this would be the output if the given size is 3:
//user inputs values for first matrix
Before adding:
Array [0] =
Array [1] =
Array [2] =
//add user inputs
After adding:
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = Array[2] =
//ask for inputs for second matrix
Before Adding
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = Array[2] =
After adding
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[2] =
I wrote the following code to achieve this (In a class called ThreeDRayRunner):
public static void print(int [][][] array)
{
for (int i=0; i<array.length; i++ )
{
for (int x=0; x<array[i].length;x++)
{
System.out.println();
System.out.print("row "+ x);
for (int j=0; j<array[i][x].length;j++)
{
System.out.print (array[i][x][j]+ " ");
}
}
}
However,I get the following error:
Exception in thread "main" java.lang.NullPointerException
at ThreeDRay.print(ThreeDRay.java:13)
at ThreeDRayRunner.main(ThreeDRayRunner.java:41)
Also, in the runner I ask the user to input the integer that will be stored in the 3D Array. To do this I ask for the size and print the 3D Array when is empty and after the given numbers are added. This is my code for that:
Scanner keyboard = new Scanner(in);
out.print("How many matrices are you going to enter? ");
int s = keyboard.nextInt();
int[][][] d3= new int [s][][];
for(int i = 0; i < S; i++)
{
out.print("What is the size of the matrix " + i + " ? ");
int size = keyboard.nextInt();
int[][] mat = new int[size][size];
out.println();
for(int r=0; r<mat.length; r++)
{
for(int c=0; c<mat[r].length; c++)
{
out.print("Enter a value for spot " + r + " - " + c );
mat[r][c]=keyboard.nextInt();
}
}
out.println("The array before setting mat at spot "+i);
ThreeDRay.print(d3);
d3[i] = mat;
out.println("The array after setting mat at spot "+i);
ThreeDRay.print(d3);
You are not instantiating the 2nd and 3rd dimensions of d3 Did you mean to do this line before your first print?
d3[i] = mat;
So it would look like this:
d3[i] = mat;
out.println("The array before setting mat at spot "+i);
ThreeDRay.print(d3);
Follow up:
It looks like you actually didn't want to set d3[i] before your first print. In that case make sure you 3 dimensions for d3 are all non-null since your print is going to print all of them and not only the one that you set to mat. Initialize your 2nd and 3rd dimensions (to 0) before you start.
int[][][] d3= new int [s][][];
for (int i=0; i < d3.length ;++i){
d3[i] = new int[0][0];
}
Given the 2d array:
double[][] table;
table = new double[4][5];
I know how to print the array with 20 0's using:
for (int ii = 0 ; ii < table.length ; ii++)
{
for (int jj = 0 ; jj < table[0].length ; jj++)
{
System.out.print(table[ii][jj] + "\t");
}
System.out.println("");
}
I would like to ask the user to input "1,2,3" where 1 is the row, 2 is the column and 3 is the value that goes in the cell. Please help me how to do this using the string split method. Thank you!
String numString = "1,2,3";
String[] splitString = numString.split(",");
int num1 = Integer.parseInt(splitString[0]);
int num2 = Integer.parseInt(splitString[1]);
int num3 = Integer.parseInt(splitString[3]);
table = new double[4][5];
table[num1][num2] = num3;
That's easy if you go step by step:
use Scanner class on System.in to read a line through nextLine()
split the String according to the given delimiter (",")
check if amount of tokens is correct
convert each token to an int through Integer.parseInt(..)
set the correct value through table[x][y] = v