Capturing Integers from Strings in Java - java

I'm attempting to capture integers from a user input using Scanner. These integers represent coordinates and a radius between 0 and 1000. It's a circle on a 2D plane.
What I have to do is to somehow capture these integers separately from one line. So, for example, the user inputs
5 100 20
Therefore, the x-coordinate is 5, the y-coordinate is 100, and the radius is 20.
The user must input all of these values on the same line, and I have to somehow capture the values from the program into three different variables.
So, I tried using this:
Scanner input = new Scanner(System.in);
String coordAndRadius = input.nextLine();
int x = coordAndRadius.charAt(0); // x-coordinate of ship
int y = coordAndRadius.charAt(2); // y-coordinate of ship
int r = coordAndRadius.charAt(4); // radius of ship
for one-digit characters, as a test. Didn't turn out so well.
Any suggestions?

Well the easiest way (not the nicest one) is just split them into array using String methods :
public static void filesInFolder(String filename) {
Scanner input = new Scanner(System.in);
String coordAndRadius = input.nextLine();
String[] array = coordAndRadius.split(" ");
int x = Integer.valueOf(array[0]);
int y = Integer.valueOf(array[1]);
int r = Integer.valueOf(array[2]);
}
You can also use nextInt method, which looks like this :
public static void filesInFolder(String filename) {
Scanner input = new Scanner(System.in);
int[] data = new int[3];
for (int i = 0; i < data.length; i++) {
data[i] = input.nextInt();
}
}
Your input will be stored in array data

Create a string array using coordAndRadius.split(" "); and extract the values from each array element.

You must split the input into 3 different string variables, each of which can be parsed separately. Use the split method to return an array, with each element containing a piece of input.
String[] fields = coordAndRadius.split(" "); // Split by space
Then you can parse each piece into an int using Integer.parseInt:
int x = Integer.parseInt(fields[0]);
// likewise for y and r
Just make sure you have 3 elements in your array before accessing it.

try this:
Scanner scanner = new Scanner(System.in);
System.out.println("Provide x, y and radius,");
int x = scanner.nextInt();
int y = scanner.nextInt();
int radius = scanner.nextInt();
System.out.println("Your x:"+x+" y: "+y+" radius:"+radius);
It will work either you will type in "10 20 24" or "10\n20\n24" where \n is of course a newline character.
And just in case you would like to know why your approach does not work here is explanation.
int x = coordAndRadius.charAt(0);
charAt(0) return first character of your string which then gets implicitly casted into int. Assume your coordAndRadius ="10 20 24". So in this case first char is '1'. So the statement above can be written as:
int x = (int)'1';

Split the values by space
String[] values = coordAndRadius.split(" ");
Then get each value as int using Integer.parseInt:
int x = Integer.parseInt(values[0]);
int y = Integer.parseInt(values[1]);
int radious = Integer.parseInt(values[2]);

Related

Trying to make a chessboard that takes simple string inputs and stores them in Java

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));
}
}

Why does this always return positive score? Simple code

I'm building simple game which places a boat on random element of array (random x and y). The goal is to guess place (this x and y). But anything I type it always return guessed.
public static void main(String [] args){
int[][] Board = new int[7][7];
int kills = 0;
Random random = new Random();
int x = random.nextInt(7);
int y = random.nextInt(7);
int boat = Board[x][y];
Scanner input = new Scanner(System.in);
while (kills < 1){
System.out.println("Where is the boat? Enter 2 digits");
System.out.println(x+""+y);
int guessX = input.nextInt();
int guessY = input.nextInt();
if (boat == Board[guessX][guessY]){
kills = kills + 1;
System.out.println("Sinked!");
}
}
}
in the code you are initializing a Board array with default value(0 in java for int)
Then you are just comparing the value in the array at a random index generated against the user input index array value.
In this case both are zero and hence it shows a match every time.
To make it work you can compare the indices guessed against the indices randomly generated to designate the boat.
int boat = Board[x][y] is going to set boat to zero. Which is the value of every element of those arrays.
To add a boat, you have to actually set one of the array elements to a value.
int boat = 1;
Board[x][y] = boat;
(Edit: and I'm not sure now if this is a real question or if the program is just some sort of late night typo.)

Java: Constructing a 2D Matrix Array According to User Input Using a Scanner

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!

JAVA populate 2D array with user input

I am trying to populate an NxN matrix. What I'd like to do is be able to enter all the elements of a given row as one input. So, for example if I have a 4x4 matrix, for each row, I'd like to enter the 4 columns in one input, then print the matrix after each input showing the new values. I try to run the following code but I get an error that reads: Exception in thread "main" java.util.InputMismatchException. Here is my code:
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in).useDelimiter(",*");
for(i =0;i<4;i++){
for(j=0;j<4;j++){
System.out.print("Enter 4 numbers seperated by comma: ");
twoDm[i][j] = scan.nextDouble();
}
}
When I get the prompt to enter the 4 numbers I enter the following:
1,2,3,4
Then I get the error.
You should just do this;
double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(System.in);
int i, j;
for (i = 0; i < 4; i++) {
System.out.print("Enter 4 numbers seperated by comma: ");
String[] line = scan.nextLine().split(",");
for (j = 0; j < 4; j++) {
twoDm[i][j] = Double.parseDouble(line[j]);
}
}
scan.close();
You should not forget to close the scanner too!
1 2 3 4 are not visible by Scanner as double numbers, but as integers.
So you have the following possibilities:
If you don't need a double use nextInt()
Write 1.0,2.0,3.0,4.0 instead of 1,2,3,4
Read the values as strings and convert them to double with Double.parseDouble()
I believe it would be easier to use string.split() , rather than .useDelimiter() , because when using delimiter , you would have to input the last number with a comma as well (since comma is the one delimiting stuffs) unless you create some regex to take both comma and \n as delimiter.
Also, you should give the prompt - System.out.print("Enter 4 numbers separated by comma: "); inside the outer loop, not the inner loop, since you would be taking in each row inside the outer loop, and only elements in each row in the inner loop.
You can do -
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in);
for(i =0;i<4;i++){
System.out.print("Enter 4 numbers separated by comma: ");
String row = scan.nextLine().split(",");
for(j=0;j<4;j++){
twoDm[i][j] = Double.parseDouble(row[j]);
}
}

convert line from text file into variables JAVA

I'm trying to extract the numbers individual lines from a text file and perform an operation on them and print them to a new text file.
my text file reads somethings like
10 2 5 2
10 2 5 3
etc...
Id like to do some serious math so Id like to be able to call upon each number from the line I'm working with and put it into a calculation.
It seems like an array would be the best thing to use for this, but to get the numbers into an array do I have to use a string tokenizer?
Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextLine()) {
String[] numstrs = sc.nextLine().split("\\s+"); // split by white space
int[] nums = new int[numstrs.length];
for(int i = 0; i < nums.length; i++) nums[i] = Integer.parseInt(numstrs[i]);
// now you can manipulate the numbers in nums[]
}
Obviously you don't have to use an int[] nums. You can instead do
int x = Integer.parseInt(numstrs[0]);
int m = Integer.parseInt(numstrs[1]);
int b = Integer.parseInt(numstrs[2]);
int y = m*x + b; // or something? :-)
Alternatively, if you know the structure ahead of time to be all ints, you could do something like this:
List<Integer> ints = new ArrayList<Integer>();
Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextInt()) {
ints.add(sc.nextInt());
}
It creates Integer objects which is less desirable, but isn't significantly expensive these days. You can always convert it to an int[] after you slurp them in.

Categories

Resources