Integers from a String to an Int array - java

I'm writing a simple tic tac toe game and need to accept user input during their turn. The player should simply provide a set of coordinates for where to place their token (1,1) to (3,3). I am supposed to be able to accept input as either "2 1" or "2,1" or "2, 1". So I need to be able to take their String input and pull out each of the two numbers, regardless of delimiter and use them to assign their token to the specified cell in the 3x3 array.
The major catch is only being able to utilize stuff we've been taught already (this is the first quarter of Java). This is the first seven chapters of Building Java Programs which consists of Scanner, conditionals/logic, loops and arrays. No patterns, matchers, lists, etc.
Is there a way to accomplish this using only the String class, scanner, or arrays?

Just using the String class, you can use String.split() to get an array of strings which can then be parsed to Integers
public class Example{
public static void main(String []args){
String str = "2 1";
// first split the original string on a comma
String[] str_arr = str.split(",");
// if the length is one then there were no commas in the input, so split again on white space
if (str_arr.length == 1){
str_arr = str.split(" ");
}
int[] int_arr = new int[str_arr.length];
// assign the string array to an int array
for (int i = 0; i < str_arr.length; i++){
int_arr[i] = Integer.parseInt(str_arr[i]);
}
// output to console
for (int j : int_arr){
System.out.println(j);
}
}
}

Updated
Forgot to add "" to convert char to String.
Scanner input = new Scanner(System.in);
String userInput;
String[] coordinates = new String[2];
char character;
int length;
userInput = input.nextLine();
length = userInput.length();
if(length > 2){
coordinates[0] = "" + userInput.charAt(0);
character = userInput.charAt(2);
if(character != ',' && character != ' '){
coordinates[1] = "" + character;
}
else{
coordinates[1] = "" + userInput.charAt(3);
}
}
Explained:
We use an Array to store the two positons you need.
We use a Character to store read in input positions.
We get the length of the read input. This is to validate if it is correct. Since the correct input should be at least more than 2 characters.
We know that the first position is valid so we assign it immediately.We also know that the second position cannot be valid so we skip it (charAt(2) and not charAt(1)) Then we check if the third position is valid if not we assign the fourth position.
Goodluck!

Related

How to separate a string user input into two different strings?

Sorry for the uninformative title, but I'm new to Java and am quite confused about how I should separate a user input (a string) into two different strings.
Essentially, what I want to do is take a user input with two of the same numbers or letters separated by a space, and remove the corresponding numbers or letters from an ArrayList of strings.
Note: the user input can be a single number or letter, and the method for this part must identify that the user input is not a single letter or number.
For example, if I have the (java) code:
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
the user then input:5 5 (5 space 5)
and if I have an ArrayList:
Arraylist<String> arrList = new ArrayList<String>;
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
How do I remove the two 5's from arrList?
My first approach was to separate the user input string into two different strings so that I could remove the two strings from the ArrayList of strings. Since both numbers or letters should be identical to each other, I would only need to scan the first integer or letter. However, I'm not quite sure how to write a method that would scan the first integer or letter in a string that consist of two numbers/integers with a space between them.
I would be much appreciated for any help! Thanks!
Simply use Collection::removeIf method:
String number = "5"; // or an user input
arrList.removeIf(item -> number.equals(item)); // number::equals
You can use .split() to split the inputs by space
String str = scan.nextLine();
String[] list = str.split(" ");
Then you can remove inputs using .remove() from ArrayList
for (int i = 0; i < list.length; i++) {
arrList.remove(list[i]);
}
You have at least two options:
Use split():
String[] numbers = str.split(" ");
Use next() instead of nextLine():
String str1 = scan.next();
String str2 = scan.next();
If you take the latter approach, you might add a hasNext() call to handle the case where there's only one string.
According to your explained example, it looks like you only want to remove the first instance of a string item from the ArrayList otherwise you wouldn't want to supply 5 5, something like this:
String ls = System.lineSeparator();
ArrayList<String> arrList = new ArrayList<>();
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
Scanner scan = new Scanner(System.in);
String str = "";
while (str.equals("")) {
System.out.print("Enter the numerical strings to delete from ArrayList seperated by a whitespace: " + ls
+ "Your Entry: --> ");
str = scan.nextLine();
if (!str.replaceAll("\\s+", "").matches("\\d+")) {
System.out.println("Invalid Entry! Entries must be numerical integer type! (" + str + ")" + ls);
str = "";
}
}
String[] numbers = str.split("\\s+");
// Iterate through all the User Supplied numbers...
for (int i = 0; i < numbers.length; i++) {
// Remove the first instance (only) of the
// current User the supplied number.
for (int j = 0; j < arrList.size(); j++) {
if (arrList.get(j).equals(numbers[i])) {
arrList.remove(j);
break;
}
}
}
// Display the ArrayList when all is done...
System.out.print(String.join(ls, arrList));
If you supply only one 5 then only the first 5 encountered within the ArrayList is removed.

How to seperate a char and num in a string and print the char repeated times of num

Write a java programm to print a output like this
input : d3f4cf5
output dddffffcfcfcfcfcf
for(int i=0; i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
{r = str.charAt(i);
for(r=1;r<=i;r++) {
System.out.println(str.substring(t, i));
t = ++i;
}
}
if (i==str.length()-1) {
for (r = 1; r <= i; r++) {
System.out.println(str.substring(t));
}
}
}
Well, as Ronald suggested you could split your string and run over the arrays.
For how to split have a look here: Java - Split String by Number and Letters
Let's assume we then just have the array ["d","3","f","4","cf","5"]. You then could do something like this:
for( int i = 0; i < array.length; i += 2 ) {
String letters = array[i];
int count = Integer.parseInt( array[i + 1] );
//loop and print here
}
Note that this always expects the string to start with at least one letter and end with a number. If it doesn't you'd have to handle that explicitly, i.e. don't print anything for the first number if it starts with a number (that could be done by just "printing" an empty string n times) and assume a count of 1 if the input ends with letters.
If you can't use regular expressions for some reason you could also do it while iterating over the characters of the string. You'd then use a combination of the following steps:
If the character is a letter you're in string building mode. You add the character to a temporay string. Initially that temporary string would be empty.
If the character is a digit you're in counting mode. You add the digit to a temporary counter (which you'd first multiply with 10 if you want to support more than one digit numbers). The counter would initially have the value 0.
When you switch from counting mode to string building mode you print the current temporary string as often as you've counted, then reset the counter to 0 and the temporary string to empty ("") and repeat step 1 (you add the current character to the temp string).
When you hit the end of the input you do the same as in step 3. If you need to support input ending in letters you'd probably want to assume a count of 1 so before executing step 3 you'd set the counter (which should still be 0) to 1.
If your input is well formed something like below should work:
public static void main(String[] args){
String input = "d3f4cf5";
System.out.println(uncompress(input));
}
private static String uncompress(String input) {
//Split input at each number and keep the numbers
// for the given input this produces [d3, f4, cf5]
String[] parts = input.split("(?<=\\d+)");
StringBuilder sb = new StringBuilder();
for(String str : parts){
// remove letters to get the number
int n = Integer.parseInt(str.replaceAll("[^0-9]", ""));
// remove numbers to get the letters
String s = str.replaceAll("[0-9]", "");
// append n copies of string to sb
sb.append(String.join("", Collections.nCopies(n, s)));
}
return sb.toString();
}

Ignoring characters using Scanner in Java

I want to take a multiple coordinate points, say (35,-21) (55,12)... from standard input and put them into respective arrays.
Let's call them x[] and y[].
x[] would contain {35, 55, ...} and y[] would contain {-21, 12, ...} and so forth.
However, I can't seem to find a way to get around the parenthesis and commas.
In c I was using the following:
for(i = 0; i < SIZE; i++) {
scanf("%*c%d%*c%d%*c%*c",&x[i],&y[i]);
}
However in Java I can not seem to find a way to get around the non-numeric characters.
I currently have the following in Java, as I am stuck.
double[] x = new double[SIZE];
double[] y = new double[SIZE];
Scanner sc = new Scanner(System.in);
for(int i=0; i < SIZE; i++) {
x[i] = sc.nextDouble();
}
So the question:
How would I ignore characters when reading in doubles from scanner?
A quick edit:
My goal is to keep the strict syntax (12,-55) on user input, and being able to enter multiple rows of coordinate points such as:
(1,1)
(2,2)
(3,3)
...
nextDouble() tries to fetch a double number from the input. It is simply not meant to parse the input stream and figure by itself how to interpret that string to somehow extract a number.
In that sense: a scanner alone simply doesn't work here. You could look into using a tokenizer - or you use scanner.next() to return the full string; to then do either manual splitting/parsing, or you turn to regular expressions to do that.
I would do it in multiple steps for improved readability. First it's the System.in retrieving using a scanner and then you split in order to get each group of coordinates separately and then you can work on them later, for whatever purposes.
Something similar to this:
Scanner sc = new Scanner(System.in);
String myLine = sc.nextLine();
String[] coordinates = myLine.split(" ");
//This assumes you have a whitespace only in between coordinates
String[] coordArray = new String[2];
double x[] = new double[5];
double y[] = new double[5];
String coord;
for(int i = 0; i < coordinates.length; i++)
{
coord = coordinates[i];
// Replacing all non relevant characters
coord = coord.replaceAll(" ", "");
coord = coord.replaceAll("\\(", ""); // The \ are meant for escaping parenthesis
coord = coord.replaceAll("\\)", "");
// Resplitting to isolate each double (assuming your double is 25.12 and not 25,12 because otherwise it's splitting with the comma)
coordArray = coord.split(",");
// Storing into their respective arrays
x[i] = Double.parseDouble(coordArray[0]);
y[i] = Double.parseDouble(coordArray[1]);
}
Keep in mind that this is a basic solution assuming the format of the input string is strictly respected.
Note that I actually cannot fully test it but there should remain only some light workarounds.
Mentioned that the user input is strictly restricted to (12,-55) or (1,1) (2,2) (3,3) ... formats the below code works fine
Double[] x = new Double[5];
Double[] y = new Double[5];
System.out.println("Enter Input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
input = input.trim();
int index = 0;
while(input != null && input != "" && input.indexOf('(') != -1) {
input = input.trim();
int i = input.indexOf('(');
int j = input.indexOf(',');
int k = input.indexOf(')');
x[index] = Double.valueOf(input.substring(i+1, j));
y[index] = Double.valueOf(input.substring(j+1, k));
System.out.println(x[index] + " " + y[index]);
input = input.substring(k+1);
index++;
}
Here I have got the user input in string format and then trim method is called on it to remove the leading and tailing white spaces.
In the while loop the substring between '(' and ',' is taken into x[] and the substring between ',' and ')' is taken into y[].
In the loop the index is incremented and the input string is modified to the substring after the first occurrence of ')' and till the end of the string.
The loop is repeated till there is no occurrence of ')' or the input is null.

Basic Hangman game in Java (mostly concerns string manipulation)

I am taking an intro class to Java and we have a project that deals with a hangman game. I have most of the code worked out but there is a bug that I can't seem to resolve.
First, the program prompts the user for a letter and one space where they think the letter goes, then the program displays a word in a series of hyphens and, if the user makes a correct guess, the letter in the corresponding hyphen is replaced with said letter.
For testing purposes, the word has been defaulted to narrow.
So if I were to guess the letter r and for space, I were to guess index 2, the program would give me:
Guess a letter: r
Guess a space: 2
Guess: --r---
The problem I am having is that when I guess the index 3 for space and try to guess the next r, the program just gives me the same output as before.
We are not allowed to use arrays or string builder because we have not talked about them yet.
Here are my variables:
// default word for testing
String blank = "narrow";
// variables to manipulate the string
String start = "";
String end = "";
String word = "";
// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";
Here is the code where the string is being manipulated.
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I think it has to do with the if statement, but I have tried some other things and they have not worked. Any help would be appreciated.
Thank you.
The problem with your code is that everytime the blank.indexOf(input) returns 2 everytime (indexOf returns the first occurance of 'r' which is 2)
You can change the condition to check if the character at the space that the user guessed is the contains the letter that the user guessed.
You can do this as follows:
Maintain the pattern to be printed. Make a variable for this.
update the pattern everytime the user guesses correctly.
Note: In the below code guess is the variable I am talking about which is initially set to "------" for the word "narrow"
// check if the space has the letter you guessed
if (blank.charAt(space) == input.charAt(0)) {
// if it has just update the pattern string to also contain the new letter
guess = guess.substring(0, space) + input + guess.substring (space + 1)
You can just print or return (if it is a method) the pattern string.
I think blank.indexOf(input) returns only the first occurrence index of that input character. So you need to use this indexOf(int ch, int fromIndex).
In your case, store index of last occurrence of the input char in some int variable, then use that as fromIndex.
int lastOccurrence = 0;
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input, lastOccurrence)) {
lastOccurrence = i;
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I would write it like this:
//set up variables
Scanner keyboard = new Scanner(System.in);
String word = "narrow";
String display = "";
for (int i = 0; i < word.length(); i++) {
display = display + "-";
}
//loop until the word is guessed
while (display.contains("-")) {
//show the user flow, take input
System.out.println("Guess: " + display);
System.out.print("Guess a letter: ");
String letter = keyboard.nextLine();
System.out.print("Guess a space: ");
String spaceStr = keyboard.nextLine();
int space = Integer.parseInt(spaceStr);
//check if the guess is right
if (letter.equals(word.charAt(space) + "")) {
//modify the string shown to the user
String temp = display.substring(space + 1);
display = display.substring(0, space);
display = display + letter + temp;
}
}
The key is to have one variable that is shown to the user and one which holds the real word. When they make a correct guess, you can modify the string which is shown to the user.
indexOf(String str) returns the index within this string of the FIRST OCCURENCE of the specified substring. More of this here
Best way I would suggest to do, is to change the output ONLY if the user got it right. Hence, for every guess I would do:
if(blank.charAt(space) == input.charAt(0))
{
start = guess.substring(0, space);
end = guess.substring(space + 1);
word = start.concat(input).concat(end);
}

Convert numbers into word-numbers (using loop and arrays)

How do I write a simple program that converts numbers into word-numbers, using loops and arrays?
like this: input: 1532
output: One Five Three Two
Here's what I tried:
class tallTilOrd
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String [] tall = {"null", "en" , "to", "tre", "fire" ,
"fem", "seks", "syv", "åtte", "ni", "ti");
System.out.println("Tast inn et ønsket tall");
int nummer = input.nextInt();
for (int i = 0; i<tall.length; i++)
{
if(nummer == i)
{
System.out.println(tall[i]);
}
}
}
}
Scanner input = new Scanner (System.in);
String in = Integer.toString(input.nextInt());
String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};
for(char c : in.toCharArray()){
int i = (int) (c-'0');
for (int j = 0; j<tall.length; j++) {
if(i == j){
System.out.print (tall[j] + " ");
}
}
}
I give you a hint:
You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)
Now I'm not sure this is the perfect way to do it, but it would be a possible one.
Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.
A few notes:
In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.
Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.
Also, note that println prints a newline each time.

Categories

Resources