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.
Related
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!
I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method
So I can't get this little snipit of code to work and I'm not sure why it wont...
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
double[] hold = double.parseDouble(rawInput.split(" "));
I have an idea to use another string array to put the values in initially then put them into the double array using a for loop and the double.parseDouble() but that seems overly complicated for what I want to do.
Your code fails to compile because rawInput.split(" ") returns an array of String objects. You need just one String object to pass to Double.parseDouble(). It looks like you'll need a loop, to iterate through the array that you get.
If only it was that simple. You will have to create a loop.
What I ended up doing was this:
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
double[] doubleHold = new double[3];
String[] stringHold = rawInput.split(" ");
for(int i = 0; i < 3; i++)
{
doubleHold[i] = Double.parseDouble(stringHold[i]);
}
I don't like how it works and think there must be a better way, anyone have that better way?
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
String[] inputs = rawInput.split(" ");
double[] values = new double[inputs.length];
for (int i = 0; i < inputs.length; i++) {
values[i] = Double.parseDouble(inputs[i]);
}
Try this!
We are asked to do the following:
Receive the first names of your family members (between 3 to 6 members of your family), create an array of String.
Write a static method called generateNewName() as following:
It receives the array of String as a parameter.
It creates a new first name by using the 2nd character of each String from the array
Example: If you enter as first names Rocky, Ashley, Ocarina, Baron, Ernest, the resulting name should be oscar.
Display the names that were entered and newly generated name
This is what I have:
import java.util.Arrays;
import java.util.Scanner;
public class Foothill {
static Scanner input;
public static void main(String[] args) {
input = new Scanner (System.in);
String[] getNames = new String[5];
char Output;
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
}
public static char generateNewName(String[] getNames)
{
String newS = Arrays.toString(getNames);
char result = '\0';
for(int j = 0; j < getNames.length; j++){
result = (char) (result + newS.charAt(1));
}
return result;
}
}
It is properly taking the input, however it seems to not be executing the generatNewName method. Am I doing something wrong with the types of methods i'm using? Should generateNewName return a string-type? If so, how do I get the second letter of all input strings and concatenate them? Thanks,
Your generateNewName() method should be returning a String, not a char.
Then you would have to change that
char result = '\0';
with
String result = "";
and then you start appending (using +) the letters to the String.
You can also read about StringBuilder, which would make the code more efficient.
Also, String newS = Arrays.toString(getNames); that line doesn't make much sense. You want to be looping through the names you have, not through all the letters of your name.
I would rewrite that loop to something like:
for (int i = 0 ; i < names.length ; i++) {
result += names[i].charAt(1);
}
or, using a for-each loop
for (String name : names) {
result += name.charAt(1);
}
"Enter 5 names:" is misleading. Consider "Enter name " + (x + 1) + " (of " + 5 + "):" or something similar.
But to answer your question: You are running generateNewName before you get any names! It's being executed for an array of only null elements!
Change this:
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
to this
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
Output = generateNewName(getNames);
System.out.println(Output);
:)
Also consider renaming your variables to (a) follow naming conventions such as variable names should be lowercase, and (b) to be more indicative of what they hold and what they are (string, char, array, etc.). Such as names or nameArray instead of getNames and newName or outputName instead of Output.
Finally, and as stated by others, you're using and returning a char in the generateNewName, and obviously a name is a string, not a char.
generateNewName should return a String, not a char. A char is a single character, like the letter A.
You can't generate the new name before asking for the old names, right? Within a method, unless you say otherwise (e.g. with a loop), code runs from top to bottom, like a list of instructions.
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.