How do i take a input from JOptionPane.showInputDialog, split it and add it to an Arraylist?
public static void main(String[] args) {
String acc = JOptionPane.showInputDialog("Enter a string:");
int num = Integer.parseInt(acc);
}
You can use Java's String.split() to separate a string based on a separatos.
For example if the words in the String are separated by a space then you can use:
yourString.split(" ");
This will return an String array. A more concrete example for what you want can be something like this
ArrayList<String> list = new ArrayList<String>();
String pop = "hello how are you doing";
for(String s: pop.split(" ")){
list.add(s);
}
The variable 'list' will contain:
["hello", "how", "are", "you", "doing" ]
EDIT: I read in another post that you wanted to parse it to integer first, you should put that kind of things in your question. If you can then it's better if you split the string with the above method and then parse each element as you add it to an Integer ArrayList (this if the elemenets are integers).
Please pay more attention to your posts. In the title you say LinkedList, in the text ArrayList. By the way will nobody figure out what you really want with that kind of information.
So you want to split something? You mean the string that you are getting there?
Then just look at this post!
How to split a string in Java
Then with the single values you simply add then to the list.
Example:
String acc = JOptionPane.showInputDialog("Enter a string:"); //enters yes-no
String[] result = acc.split("-");
myArrayList.add(result[0]); //yes
myArrayList.add(result[1]); //no
Component frame = new JFrame();
// get text
String name = JOptionPane.showInputDialog(frame, "What's your name?");
System.out.println(name);
// split text when u get a space
List<String> list = Arrays.asList(name.split("\\p{Z}+"));
System.out.println(list);
Related
I have an array list that contains a number for someone's score in a race and next to it is an F or M for gender
for example, "34 F" or "23 M"
I need to find the minimum female and the minimum male value, but I don't know how to separate the int and the char in an array list
The Scanner class is particularly good at this. It has all the splitting and parsing functionality built in. The methods you want are nextInt() and next(), for getting the tokens and converting them as necessary. By default, any kind of white space is used as the delimiter, but you can change the Scanner to use different delimiters.
Scanner scanner = new Scanner(myString);
int age = scanner.nextInt();
String gender = scanner.next();
Suppose myString is "24 M". Then this code will set age and gender to 24 and "M" respectively. No need for split or parseInt.
Don't attach your code?...
String[] result = "34 F".split("\\s+");
Integer score = Integer.parseInt(result[0]);
String gender = result[1];
you can iterate over the list then simply split each of the strings with a space delimiter.
for example:
import java.util.*;
public class GFG {
public static void main(String args[])
{
String person = "35 F";
String[] arrOfStr = person.split(" ",2);
Integer age= Integer.parseInt(arrOfStr[0]);
String sex=arrOfStr[1];
System.out.println(age+" "+sex);
}
}
This is the string that i use
String [] hi = {"hello","hi","whats up"};
I want the program to display one of the words in the string every time the user types "hi" but my code can't compare the user input and the string
do{
System.out.println("You:");
s.next();
String[] userinput={"hi"};
if(userinput.equals("hi")){
Random r = new Random();
rno = r.nextInt(3);
System.out.println("bot:"+hi[rno]);
}
else{
System.out.println("Bot:Bye");
}
}while(true);
please help
You compare an array of Strings with a String. This will always return false as the types are different.
Instead you could use the contains method of a Collection. Example:
List<String> userInput = Arrays.asList("hi");
if (userInput.contains("hi")) {
//Do something
}
userinput is String[], you need to compare between String as
userinput[0].equals("hi")
userinput will never equal "hi" because "hi" is a String object, and userinput is a String[] (string array) object.
If userinput is supposed to be an array (a bunch of strings), then you would need to compare by doing the following:
for(String s:userinput){
if(s.equals("Hi")){
//do whatever you want to do when this happens
}
}
If userinput is always going to be a single string then you should say
String userinput = "Hi";
use Map Instead
Map<String,String>map=new HashMap<String,String>();
map.put("Hello","Hi");
System.out.println(map.get(s.next()).toString());
You are comparing a String Array to a String. Try userInput[0].equals("hi")
I'm trying to make a calculator to help me with physics homework. For this, I'm trying to make it separate input into two parts, so typing "wavelength 18" would split it into "wavelength" and "18" as a numeric value.
I understand to get the first word that I can use
String variable = input.next();
But is there a way to read what comes after the space?
Thanks.
String[] parts = variable.split(" ");
string first = parts[0];
string second = parts[1];
String entireLine = input.nextLine();
String [] splitEntireLine = entireLine.split(" ");
String secondString = splitEntireLine[1];
Assuming that you also might have three words or just one, it is better not to rely on arrays. So, I suggest to use List here:
final String inputData = input.next();
//Allows to split input by white space regardless whether you have
//"first second" or "first second"
final Pattern whiteSpacePattern = Pattern.compile("\\s+");
final List<String> currentLine = whiteSpacePattern.splitAsStream(inputData)
.collect(Collectors.toList());
Then you can do a variety of checks to ensure you have correct number of values in the list and get your data:
//for example, only two args
if(currentLine.size() > 1){
//do get(index) on your currentLine list
}
I am working on a java problem at the moment where I am creating a program that simulates the old TV quiz show, You Bet Your Life. The game show host, Groucho Marx, chooses a secret word, then chats with the contestants for a while. If either contestant uses the secret word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code so far:
import java.util.Scanner;
public class Groucho {
String secret;
Groucho(String secret) {
this.secret = secret;
}
public String saysSecret(String line) {
if(secret.equals(line)){
return ("true");
} else {
return ("false");
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
}
}
In the main method I need to now create a new Groucho object with a secret word from the first line of standard input (in.nextLine()).
I am not sure how I go about doing this? Can someone explain please!
Thanks!
Miles
Have a look at the Scanner API, and perhaps the Java Tutorial on Objects. And that on Strings.
Learning the basics is usually more useful than just getting a line of code from somewhere.
No offence :).
You can read the line with the following statement:
String line = in.nextLine();
Then, if you'd like to have the first word (for example), you can split the line and create a new Groucho object.
String split = line.split(" ");
Groucho g = new Groucho(split[0]);
Here you can find more information about :
Scanner
String.split()
You would create a new Groucho object and pass in in.nextLine() as a parameter. This would be done by Groucho g = new Groucho( in.nextLine() );
You will need something that looks like this:
Scanner in = new Scanner(System.in); //take in word
String secretWord = in.nextLine(); //put it in a string
Groucho host = new Groucho (secretWord); //create a Groucho object and pass it the word
in.nextLine() will take a single line of the whole input, so you can simply pass it into the constructor.
For example:
String inputWord = in.nextLine();
Groucho g = new Groucho(inputWord);
In the Scanner class the nextLine() method takes the next line of input as a String. You can save that line of input to a String variable:
String line = in.nextLine();
Now that you have a full line of input, you can get the first word from it.
In a sentence each word is separated from other words by a space. In the String class the split() method can split a String into an array of smaller strings, such as words in a sentence, with a given separator, such as a space (" "), that you specify as a parameter:
String[] words = line.split(" ");
Next you can choose a secret word from the array by selecting the appropriate index.
For the first word:
String chosenWord = words[1];
For the last word:
String chosenWord = words[words.length - 1];
For a random word:
String chosenWord = words[Math.floor(Math.random() * words.length)];
Now you can simply pass on the secret word as a parameter to a new Groucho constructor:
Groucho secretWord = new Groucho(chosenWord);
This step by step explanation created a new variable at each step. You can accomplish the same task by combining multiple lines of code into a single statement and avoid creating unnecessary variables.
In Java, How can I store a string in an array? For example:
//pseudocode:
name = ayo
string index [1] = a
string index [2] = y
string index [3] = o
Then how can I get the length of the string?
// this code doesn't work
String[] timestamp = new String[40]; String name;
System.out.println("Pls enter a name and surname");
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
name=timestamp.substring(0, 20);
If you want a char array to hold each character of the string at every (or almost every index), then you could do this:
char[] tmp = new char[length];
for (int i = 0; i < length; i++) {
tmp[i] = name.charAt(i);
}
Where length is from 0 to name.length.
This code doesn't compile because the substring method can only be called on a String, not a String array if I'm not mistaken. In the code above, timestamp is declared as a String array with 40 indexes.
Also in this code, you're asking for input from a user and assigning it to name in this line:
name = sc.nextLine();
and then you are trying to replace what the user just typed with what is stored in timestamp on the next line which is nothing, and would erase whatever was stored in name:
name = timestamp.substring(0,20);
And again that wouldn't work anyway because timestamp is an array of 40 strings instead of one specific string. In order to call substring it has to be just one specific string.
I know that probably doesn't help much with what you're trying to do, but hopefully it helps you understand why this isn't working.
If you can reply with what you're trying to do with a specific example I can help direct you further. For example, let's say you wanted a user to type their name, "John Smith" and then you wanted to seperate that into a first and last name in two different String variables or a String array. The more specific you can be with what you want to do the better. Good luck :)
BEGIN EDIT
Ok here are a few things you might want to try if I understand what you're doing correctly.
//Since each index will only be holding one character,
//it makes sense to use char array instead of a string array.
//This next line creates a char array with 40 empty indexes.
char[] timestamp = new char[40];
//The variable name to store user input as a string.
String name;
//message to user to input name
System.out.println("Pls enter a name and surname");
//Create a scanner to get input from keyboard, and store user input in the name variable
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
//if you wanted the length of the char array to be the same
//as the characters in name, it would make more sense to declare it here like this
//instead of declaring it above.
char[] timestamp = new char[name.length()];
//For loop, loops through each character in the string and stores in
//indexes of timestamp char array.
for(int i=0; i<name.length;i++)
{
timestamp[i] = name.charAt(i);
}
The other thing you could do if you wanted to just seperate the first and last name would be to split it like this.
String[] seperateName = name.split(" ");
That line will split the string when it finds a space and put it in the index in the seperateName array. So if name was "John Smith", sperateName[0] = John and seperateName[1] = Smith.
Are you looking for a char[]? You can convert a character array to a String using String.copyValueOf(char[]).
Java, substring an array:
Use Arrays.copyOfRange:
public static <T> T[] copyOfRange(T[] original,
int from,
int to)
For example:
import java.util.*;
public class Main{
public static void main(String args[]){
String[] words = new String[3];
words[0] = "rico";
words[1] = "skipper";
words[2] = "kowalski";
for(String word : words){
System.out.println(word);
}
System.out.println("---");
words = Arrays.copyOfRange(words, 1, words.length);
for(String word : words){
System.out.println(word);
}
}
}
Prints:
rico
skipper
kowalski
---
skipper
kowalski
Another stackoverflow post going into more details:
https://stackoverflow.com/a/6597591/445131