Why is my string not splitting? [closed] - java

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+");

Related

Can not use the split() method [closed]

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");
}
}
}

Sorting ArrayList Collections.sort not working [closed]

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);
}

"letter finder" code to find the number of letters in a word [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
import java.util.Scanner;
public class lettercounter {
public static void main(String[] args) {
Scanner lettercounter = new Scanner(System.in);
System.out.println("Enter your sentence > ");
String sentence = lettercounter.nextLine();
int length = sentence.length();
System.out.println("what letter do you seek? > ");
String letters = lettercounter.nextLine();
char letter = letters.charAt(0);
int counter = 0;
for (int i = 0; i < length + 1; i++) {
char digit = sentence.charAt(i);
if (Character.toString(digit).matches(Character.toString(letter))) {
counter++;
}
}
System.out.println("Number of '" + letter + "'s found >" + counter + "");
}
}
whats wrong with the code?? i tried doing this but there seems to be an error when i run it: it says
xception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at lettercounter.main(lettercounter.java:15)
i<length+1 should be i<length.
This fixes the problem because there are only length characters in the string, accessible via sentence.charAt(0) up to sentence.charAt(length - 1). You are trying to access one more character - sentence.charAt(length).

String Input line 4 Error, I cannot seem to figure out what it is [closed]

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 8 years ago.
Improve this question
import java.io.*;
public class StringInput{
public static void main (String args[]);{
String Name "StringInput";
System.out.print ("Enter your name: ");
InputStreamReader input = new InputStreamReader(System.in);
InputStreamReader reader = new BufferedReader(input);
name = reader.readline();
catchException e;{
}//Exception
System.out.println ("Hello"+Name+"How are you?");
}//main
}//class
That is the code that I was doing, theres one error. Line 4, I can't figure out what it is.
We were doing it in class (I just started Computer Programming 12) and we didn't have time to finish it and everything.
If someone could help me figure out what is wrong with line 4 that'd be really helpful.
Thanks ! :)
Removed the semi colon, still get String Name "StringInput";
^
1 error
Process completed.
Remove the semicolon(;) after main method:
Change this:
public static void main (String args[]);{
to
public static void main (String args[]) {
Another error in your code is related to try/catch usage:
Change this:
name = reader.readline();
catchException e;{
}//Exception
to
try {
name = reader.readline();
catch(Exception e){
e.printStackTrace();
}//Exception
Final Note: Learn the language syntax first before jumping to coding.

This method won't work... Is it a syntax error? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
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.
Improve this question
So, I've been having issues with this. I'm trying to make this method return the first character of the string given to it, but I keep getting java.util.NoSuchElementException... I think I may be using some syntax wrong but really I have no idea. Any help?
public static char nthChar (){
Scanner sc = new Scanner(in);
String input = sc.nextLine();
char [] userCharArray = new char[input.length()];
userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Note that I imported the static members of java.lang.System
I changed it to this...
public static char nthChar (){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
char [] userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Still doesn't work.
This looks like the suspect to me:
sc.close();
When you close that Scanner, you are also closing System.in. Subsequent reads from a new Scanner reading from System.in will throw NoSuchElementException because the underlying stream is closed.
So you need to remove that and also look through your code and make sure you are not closing System.in elsewhere. Although usually you should close your streams when you are done with them, System.in is a special case and you don't need to (and shouldn't) close a stream that's reading from it.
For example, this will throw a NoSuchElementException:
Scanner in1 = new Scanner(System.in);
in1.close();
Scanner in2 = new Scanner(System.in);
String line = in2.nextLine(); // throws the exception

Categories