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
Related
I am trying to make program that have a different behavior when the user inputs certain arguments to a String that is received by the program through a Scanner. My problem is the fact that i want to make it as if the user doesn't write the 2nd argument for example, the program should still work.
static String ReadString() {
Scanner scan = new Scanner(System.in);
return scan.nextLine();
}
String command = ReadString();
String words[]=new String[4];
words[0]="empty";
words[1]="empty";
words[2]="empty";
words[3]="empty";
words = command.split(" ");
The problem is that if I am calling for example words[1] after the user has written only one argument to that string, I still get the error ArrayOutOfBounds, although there should be an string with the value "empty".
Example:
User writes : ababbbbb command1 >>> when I call words[1] it should give me command1
User writes : ababbbbb >>> when I call words[1] it should give me empty
Because, when you wrote below code that means words which is Array of String type is pointing to reference, which is allocated memory to hold 4 string.
String words[]=new String[4];
Now, below line of code where you are creating Array by spliting them by " " has only size 1. Now, words variable reference has changed and it can only hold 1 String.
words = command.split(" ");
You need to make following correction :
String command = ReadString();
String words[]=new String[4];
String[] n = command.split(" ");
for(int i=0; i< 4; i++)
{
if((n.length-1)==i)
{
words[i]=n[i];
}
else
{
words[i]="empty";
}
}
>>>Demo<<<
I am just starting out in Java so I appreciate your patience. Anyways, I am writing a word count program as you can tell by the title, I am stuck at the numWords function below the for loop, I am not sure what I should set it equal to. If someone could set me in the right direction that would be awesome. Thank you. Here is all of my code thus far, let me know if I not specific enough in what I am asking, this is my first post. Thanks again.
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s\
+");
for(int i = 0; i < words.length; i++){
numWords = 0;
}
}
}
}
If your code is intended to just count words, then you don't need to iterate through the words array at all. In other words, replace your for loop with just:
numWords += words.length;
Most likely a simpler approach would be to look for sequences of alpha characters:
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find())
numWords++;
If you need to do something with the words (such as store them in a map to a count) then this approach will make that simpler:
Map<String,Integer> wordCount = new HashMap<>();
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find()) {
String word = wordMatch.group();
int count = wordCount.getOrDefault(word, 0);
wordCount.put(word, count + 1);
}
Don't worry. We were all beginners once.
First of all, you don't need to do the loop because "length" attribute already has it. But, if you want to practice with loops is so easy as increasing the counter each time the iterator advances and that's it.
numWords++;
Hint: Read the input
String sentence = stdin.nextLine();
Split the string
String [] words = sentence.split(" ");
Number of words in a sentence
System.out.println("number of words in a sentence are " + words.length);
You mentioned in comments that you would also like to print the line in alphabetical order. For that Java got you covered:
Arrays.sort(words);
The best way to count the amount of words in a String String phrase is simply to get a String array from it using the String method split String[] words = phrase.split(" ") and giving it as argument the space itself, this will return a String array with each different words, then you can simple check its lengthwords.length and this will give you the exact number.
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);
My code takes each word from a line and separates them into Tokens by spaces. There should only be 6 categories of tokens on each line if there is any more or less an Error would print.The problem is when there are dogs with a space between their name like German Shepard. My code counts it as an error.
If the Dog name German Shepard I want my code to count it as one token like "German Shepard".
ArrayList<Dog> dogs = new ArrayList<Dog>();
int numLine= 0;
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
numLine++;
String[] fields =line.split("\\s+");
if(fields.length != 6)
{
System.out.println(line);
System.out.println("ERROR ON LINE #"+numLine+
":number of fields on line must be 6, not "+ fields.length);
System.out.println();
}
// got from Dr. Koch email infromation
try{
StringTokenizer stk = new StringTokenizer(line);
String name = stk.nextToken();
String breed = stk.nextToken();
int month = Integer.parseInt(stk.nextToken());
int day = Integer.parseInt(stk.nextToken());
int year = Integer.parseInt(stk.nextToken());
double weight = Double.parseDouble(stk.nextToken());
Dog list = new Dog(name, breed, month, day, year, weight);
dogs.add(list);
}
catch(Exception missError)
{
}
}
// close the file
sc.close();
Before checking for no. of words in a line, Use regex and concatenate tokens.
Like,
String pattern = "([A-Z][a-z]+)(\s)([A-Z][a-z]+)";
line = line.replaceAll(pattern, "$1_$3");
Then split the line by space and check for the number of words, say 6 or whatever number you want.
You need to re-think how you tokenize your line. If whitespace is valid in a value, such as your German Shepherd example, you cannot use whitespace as your delimiter. You could follow Gonza's suggestion of using '|' or ';', provided these will not appear in your values (unlikely, based on your description). Personally, when reading from a file, I tend to go with a unicode character that is untypable, such as an upper case Omega - "\u03A9".
Another option would be to surround all the values with double quotes, like so:
"Fido" "German Shepherd" "01" "01" "2014" "40"
You could then extract the values using a regular expression. Something along the following lines:
public String[] getDogRecord(String fieldList)
{
final int DOG_FIELD_COUNT = 6;
final String DOG_FIELD_REGEX = "\"([^\"]+)\"\\s*";
final Pattern FIELD_PTTRN = Pattern.compile(DOG_FIELD_REGEX);
int fieldCount = 0;
Matcher fieldMatcher = FIELD_PTTRN.matcher(fieldList);
String[] dogRecord = new String[DOG_FIELD_COUNT];
// First, check we have the right number of fields
if (!fieldList.matches("(" + DOG_FIELD_REGEX + "){" + DOG_FIELD_COUNT + "}"))
throw new IllegalArgumentException("Incorrect number of fields in record!");
// Read each field into an array
while (fieldMatcher.find())
{
dogRecord[fieldCount] = fieldList.substring(fieldMatcher.start(1),
fieldMatcher.end(1));
fieldCount++;
}
return dogRecord;
}
You would of course need to parse the appropriate array entries when creating your Dog object. Alternatively, you could modify the above to return a Dog object directly.
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.