Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to split a string which is an array element but the compiler say : type mismatch, can not convert from String[] to String. I don't understand because if we have an array of string the elements of this arrays must be of type String not String[]
This is the code:
while((s=buffereader.readLine())!=null)
{
words=s.split(" ");
for (String word : words)
{
s=words[0];
s=s.split("T");
}
}
Your compiler is erroring on s=s.split("T"); where s is a string, and not an array.
Simlarly, words.equals(input) doesn't do what you expect because an array will never equal a String. You would need to scan the array to see if any element was equal. If you use a modern IDE rather than compile in the CLI, then you may catch this error quicker.
Assuming you want to check if input is contained within each line, then split the first column on the letter T, this is what you want.
String s;
List<String> words;
while((s=buffereader.readLine()) != null) {
words = Arrays.asList(s.split("\\s+")); // Split by one _or more_ spaces
if (words.contains(input)) {
s = words.get(0);
words = Arrays.asList(s.split("T"));
}
}
i found the issue. this is what i tried to do
public static void timeStamp() throws IOException {
File log= new File(parametrization.link[15]);
FileReader fileReader = new FileReader(log);
BufferedReader buffereader = new BufferedReader(fileReader);
String s;
String[] s1;
String[] words;
String input="gracefully";
while((s=buffereader.readLine())!=null)
{
words=s.split(" ");
for (String word : words)
{
if (word.equals(input));
{
s=words[0];
s1=s.split("T");
}
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I can see that this topic has been heavily discussed, however, I was not able to find an answer to my problem within previous discussions. That being said, I have a very simple problem where I want to ask a user to input a list of cities. After being entered, I am storing the list in an ArrayList cities and using collections.sort to sort them. For some reason, collections.sort is not sorting my ArrayList. Example: User input is "Atlanta, Washington DC, New York". My output, when running the program, is unsorted.
public class CitySortDemo {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
cities.add(input.nextLine());
Collections.sort(cities);
for (int i = 0; i < cities.size(); i++){
System.out.println(cities.get(i));
}
}
}
Your code adds a single string to the collection, "Atlanta, Washington DC, New York". A collection with only one entry is unaffected by sorting. :-)
You probably meant to break that string up, perhaps by splitting it on a comma:
cities.addAll(Arrays.asList(input.nextLine().split("\\s*,\\s*")));
Live Example
That splits the one string into an array of them on a comma optionally preceded and/or followed by whitespace, and adds them all to the collection.
Either you can ask the user how many cities are expected to sort or specify a character that when it is seen, stop taking input and sort them. In this your code, it just takes one line as a string. For example, it takes cities until the user enters the specifier character in which the code is ! then sort.
import java.util.*;
class CitySortDemo {
public static void main(String[] args) {
final String specifier = "!";
String str;
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
str = input.nextLine();
while (! str.equals(specifier)) {
cities.add(str);
str = input.nextLine();
}
Collections.sort(cities);
cities.forEach(System.out::println);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a requirement where I need to check if an input string contains only those words I treat as valid and every other word as invalid.
For example: Assume valid words as 'apple','orange' and 'potato'. When an input string "There is apple and orange" is given, I need to flag an error because I expect the string to contain 'apple' or 'orange' or both but not words like "There" "is" and "and". How can I do this using Java Regex? or what other options I have?
Split into words, copy into a set (or list), then use Collection.removeAll to remove the allowed words, leaving only the "invalid" ones:
Set<String> invalidWords = new HashSet<>(input.split("\\s+"));
invalidWords.removeAll(allowedWords);
System.out.println(invalidWords);
put the valid words in a set
split the string into individual words
verify that the set contains all the words
Split your input so you have individual words, then check if each one is valid:
public static void main(String[] args){
List<String> allowed = Arrays.asList("apple", "orange", "potato");
String input = "There is apple and orange";
System.out.println(isValid(input, allowed));
}
boolean isValid(String input, List<String> allowed){
String[] words = input.split("\\s+");
for(String word:words){
if(!allowed.contains(word)){
return false;
}
}
return true;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Example code:
import java.util.Scanner;
public class Split {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a few words: ");
String wordsWhole = scan.next();
String[] wordsSplit = new String[4];
wordsSplit = wordsWhole.split("//s+");
System.out.println("Second word: " + wordsSplit[1]);
}
}
The output:
Enter a few words: Why no work
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
at test.Split.main(Split.java:12)
My String isn't splitting into the array like I would expect it to. Any ideas on why this is?
Line 12:
System.out.println("Second word: " + wordsSplit[1]);
There are several problems:
Scanner.next() will only return the first word (space-separated) in the input, use Scanner.nextLine() to get the entire line.
I'm guessing you're trying to split by spaces. If so, you should use backslashes rather than forward slashes in your regex ("\\s+").
You don't need to allocate the array before assigning it to the result of the split. Just use String[] wordsSplit = wordsWhole.split("\\s+");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Am having a txt file. which is having line like
if(true) return true;
I need to get the sub string from preceding spaces that is
" if(true) "
and another sub string as
" retrun true; "
I am reading this line using scanner class and assign to a string. from that string am converting it into toCharArray. I have tried using toCharArray[] but the spaces are ignored. How to get the substring from the preceding spaces using toCharArray
kindly anybody help me to get a solution for this issue
Thanks in advance.
You can use StringReader:
String str = "Some String";
int numberOfChars = str.length();
StringReader sr = new StringReader(str);
char[] chars = new char[numberOfChars];
int i = 0, read = 0;
try {
while ((read = sr.read()) != -1) {
chars[i] = (char)read;
i++;
}
} catch (IOException e) {
// handle the exception
}
This will read all the characters, without skipping any of them.
EDIT:
Now that I understand what you are trying to do, I would recommend you to define a grammar for your instructions. In this way you should be able to identify these 2 separate statements or instructions. I would suggest you to use a compiler building tool for that like e.g. ANTLR.
I have found one solution by using Regular expression for this question. The answer is as follows
public class Test{
public static void main(String[] args){
String str = " TestProgram";
Pattern pattern = Pattern.compile("\\s*[a-zA-Z0-9]+$");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(0,matcher.end());
}
}
}
Thanks
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hello, I want to read a file, file.txt that contains word pairs like this...
mot;word
oui;yes
utiliser;use
comment;how
After reading this file.txt , I want to split this text and put the French words in an ArrayList and the English words in an another ArrayList.
Thanks in advance...
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
List<String> frenchList = new ArrayList<String>();
List<String> englishList = new ArrayList<String>();
File file = new File("C:/dico.txt");
if(file.exists()){
try {
list = Files.readAllLines(file.toPath(),Charset.defaultCharset());
} catch (IOException ex) {
ex.printStackTrace();
}
if(list.isEmpty())
return;
}
for(String line : list){
String [] res = line.split(";");
frenchList.add(res[0]);
englishList.add(res[1]);
}
}
With this code you have de french word in the list "frenchlist" and the english words in the list "englishlist"
This looks like CSV file. Consider using CSV reader library.
Use String#split function from JDK and read file line by line with Scanner:
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line using String#split function
}
In while loop add splited data to ArrayList.
All information are already on stackoverflow.
Read String line by line in Java
How to split a comma separated String while ignoring escaped commas?
Reading File by line instead of word by word
Read line using Java New I/O
CSV API for Java
First, you have to create two array lists..
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
Then, open the file, read line by line, split it bye ";" and add the words to ArrayLists...
try(BufferedReader in = new BufferedReader(new FileReader("file.txt"))){
String line;
while((line = in.readLine())!=null){
String[] pair = line.split(";");
french.add(pair[0]);
english.add(pair[1]);
}
}
mot;word
oui;yes
utiliser;use
comment;how
It appears that the structure of each line is
frenchWord;englishWord
So you can read each line of your file using a Scanner (using the constructor Scanner(File source)) and the nextLine() method, and split each line by ";".
The first element in the array will be the french word and the second one the english word.
Add those element in two separate List (ArrayList per example), one containing all the french words, and the other one the english words.