If I have a line of integers in a text file in the following format:
[3, 3, 5, 0, 0]
how can I go about adding the integers into an arraylist?
I have this, but it isn't working:
while (input.hasNextInt())
{
int tempInt = input.nextInt();
rtemp.add(tempInt);
}
How do I deal with the commas and the brackets?
You can use ReplaceAll(String regex, String replacement) to remove the brackets and then use Split() function to split the string into an ArrayList using ", " as your delimiter. This will however split the String into smaller strings containing only the numbers so use Integer.parseInt() to convert the string to int.
You need to remember that the numbers in a file are strings, and need to be converted to actual integers first. Assuming that in the input file each line has the format described (example: [3, 3, 5, 0, 0]) this should work for adding all of the numbers to a single ArrayList, ignoring spaces, brackets and commas:
BufferedReader in = new BufferedReader(new FileReader("file.txt"));
List<Integer> ints = new ArrayList<Integer>();
String line = in.readLine();
while (line != null) {
String[] numbers = line.split("[\\[\\],\\s]+");
for (int i = 1; i < numbers.length; i++)
ints.add(Integer.parseInt(numbers[i]));
line = in.readLine();
}
in.close();
Untested but this should work.
string s = "[1,2,3,4,5]";
ArrayList list = new ArrayList();
foreach (string st in s.Replace("[", "").Replace("]", "").Split(','))
{
list.Add(int.Parse(st));
}
You can read the entire string and use regular expression or also the string tokenizer
//you already know how to read those lines into Strings.
String s="[3, 3, 5, 0, 0]";
StringTokenizer tokenizer = new StringTokenizer(s, "[,]");
while(tokenizer.hasMoreTokens())
list.add(Integer.parseInt(tokenizer.nextToken())
java.util.StringTokenizer will help you in splitting the String using the specified delimiters("[","," or a "]")
Refer http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
You can try something like this:
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] nums = line.substring(1,line.length() - 1).split(",");
for(String n:nums){
list.add(Integer.valueOf(n));
}
}
You could also use a regex for this purpose.
Related
I'm trying out PetitParser for parsing a simple integer list delimited by commas. For example: "1, 2, 3, 4"
I tried creating a integer parser and then use the delimitedBy method.
Parser integerParser = digit().plus().flatten().trim().map((String value) -> Integer.parseInt(value));
Parser listParser = integerParser.delimitedBy(of(','));
List<Integer> list = listParser.parse(input).get();
This returns a list with the parsed integers but also the delimiters.
For example: [1, ,, 2, ,, 3, ,, 4]
Is there a way to exclude the delimiters from the result?
Yes, there is:
Parser listParser = integerParser
.delimitedBy(of(','))
.map(withoutSeparators());
To get withoutSeparators() import import static org.petitparser.utils.Functions.withoutSeparators;.
Here is an example of how to do it without any external library:
public static void main(String args[]) {
// source String
String delimitedNumbers = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
// split this String by its delimiter, a comma here
String[] delimitedNumbersSplit = delimitedNumbers.split(",");
// provide a data structure that holds numbers (integers) only
List<Integer> numberList = new ArrayList<>();
// for each part of the split list
for (String num : delimitedNumbersSplit) {
// remove all whitespaces and parse the number
int n = Integer.parseInt(num.trim());
// add the number to the list of numbers
numberList.add(n);
}
// then create the representation you want to print
StringBuilder sb = new StringBuilder();
// [Java 8] concatenate the numbers to a String that delimits by whitespace
numberList.forEach(number -> sb.append(number).append(" "));
// then remove the trailing whitespace
String numbersWithoutCommas = sb.toString();
numbersWithoutCommas = numbersWithoutCommas.substring(0, numbersWithoutCommas.length() - 1);
// and print the result
System.out.println(numbersWithoutCommas);
}
Note that you don't need to trim() the results of the split String if you have a list without whitespaces.
In case you need the PetitParser library, you will have to look up how to use it in its docs.
With a bit more code I got the result without the delimiters:
Parser number = digit().plus().flatten().trim()
.map((String value) -> Integer.parseInt(value));
Parser next = of(',').seq(number).map((List<?> input) -> input.get(1)).star();
Parser parser = number.seq(next).map((List<List<?>> input) -> {
List<Object> result = new ArrayList<>();
result.add(input.get(0));
result.addAll(input.get(1));
return result;
});
I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?
the code:
else if(answer.equals("new"))
{
System.out.println("Enter words, separated by commas and spaces.");
String input= scanner.next();
char[] words= input.toCharArray();
Arrays.sort(words);
String sorted= new String(words);
System.out.println(sorted);
}
Result: " ,ahy "
You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray(). What you need to do is read in all of the words and add them to a String []. After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.
You'll need to split your string into words instead of characters. One option is using String.split. Afterwards, you can join those words back into a single string:
System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();
String[] words = input.split(",| ");
Arrays.sort(words);
StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(words[i]);
}
String sorted = sb.toString();
System.out.println(sorted);
Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question.
So I'm trying to read some numbers from a file and put them into an array. I've been reading about people having problems with whitespace, so using trim, I did it like this:
String[] tokens = new String[length];
for(int i = 0; i<length;i++){
String line = fileReader.nextLine();
line = line.trim();
tokens = line.split("");
}
But the first element this array (token[0]) becomes empty. Am I using the split function wrong?
You need to tell the split method what character it should split on. Try this:
tokens = line.split(" "); //split on a space character
tokens = line.split(" ");
You forgot whitespace.
I got a string with a bunch of numbers separated by "," in the following form :
1.2223232323232323,74.00
I want them into a String [], but I only need the number to the right of the comma. (74.00). The list have abouth 10,000 different lines like the one above. Right now I'm using String.split(",") which gives me :
System.out.println(String[1]) =
1.2223232323232323
74.00
Why does it not split into two diefferent indexds? I thought it should be like this on split :
System.out.println(String[1]) = 1.2223232323232323
System.out.println(String[2]) = 74.00
But, on String[] array = string.split (",") produces one index with both values separated by newline.
And I only need 74.00 I assume I need to use a REGEX, which is kind of greek to me. Could someone help me out :)?
If it's in a file:
Scanner sc = new Scanner(new File("..."));
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's all one giant string, separated by new-lines:
String oneGiantString = "1.22,74.00\n1.22,74.00\n1.22,74.00";
Scanner sc = new Scanner(oneGiantString);
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's just a single string for each:
String line = "1.2223232323232323,74.00";
System.out.println(line.replaceFirst(".*?,", ""));
Regex explanation:
(\r?\n)? means an optional new-line character.
. means a wildcard.
.*? means 0 or more wildcards (*? as opposed to just * means non-greedy matching, but this probably doesn't mean much to you).
, means, well, ..., a comma.
Reference.
split for file or single string:
String line = "1.2223232323232323,74.00";
String value = line.split(",")[1];
split for one giant string (also needs regex) (but I'd prefer Scanner, it doesn't need all that memory):
String line = "1.22,74.00\n1.22,74.00\n1.22,74.00";
String[] array = line.split("(\r?\n)?.*?,");
for (int i = 1; i < array.length; i++) // the first element is empty
System.out.println(array[i]);
Just try with:
String[] parts = "1.2223232323232323,74.00".split(",");
String value = parts[1]; // your 74.00
String[] strings = "1.2223232323232323,74.00".split(",");
I am new to Java and looking for some help with Java's Scanner class. Below is the problem.
I have a text file with multiple lines and each line having multiple pairs of digit.Such that each pair of digit is represented as ( digit,digit ). For example 3,3 6,4 7,9. All these multiple pairs of digits are seperated from each other by a whitespace. Below is an exampel from the text file.
1 2,3 3,2 4,5
2 1,3 4,2 6,13
3 1,2 4,2 5,5
What i want is that i can retrieve each digit seperately. So that i can create an array of linkedlist out it. Below is what i have acheived so far.
Scanner sc = new Scanner(new File("a.txt"));
Scanner lineSc;
String line;
Integer vertix = 0;
Integer length = 0;
sc.useDelimiter("\\n"); // For line feeds
while (sc.hasNextLine()) {
line = sc.nextLine();
lineSc = new Scanner(line);
lineSc.useDelimiter("\\s"); // For Whitespace
// What should i do here. How should i scan through considering the whitespace and comma
}
Thanks
Consider using a regular expression, and data that doesn't conform to your expectation will be easily identified and dealt with.
CharSequence inputStr = "2 1,3 4,2 6,13";
String patternStr = "(\\d)\\s+(\\d),";
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
// Get all groups for this match
for (int i=0; i<=matcher.groupCount(); i++) {
String groupStr = matcher.group(i);
}
}
Group one and group two will correspond to the first and second digit in each pairing, respectively.
1. use nextLine() method of Scanner to get the each Entire line of text from the File.
2. Then use BreakIterator class with its static method getCharacterInstance(), to get the individual character, it will automatically handle commas, spaces, etc.
3. BreakIterator also give you many flexible methods to separate out the sentences, words etc.
For more details see this:
http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html
Use the StringTokenizer class. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
//this is in the while loop
//read each line
String line=sc.nextLine();
//create StringTokenizer, parsing with space and comma
StringTokenizer st1 = new StringTokenizer(line," ,");
Then each digit is read as a string when you call nextToken() like this, if you wanted all digits in the line
while(st1.hasMoreTokens())
{
String temp=st1.nextToken();
//now if you want it as an integer
int digit=Integer.parseInt(temp);
//now you have the digit! insert it into the linkedlist or wherever you want
}
Hope this helps!
Use split(regex), more simple :
while (sc.hasNextLine()) {
final String[] line = sc.nextLine().split(" |,");
// What should i do here. How should i scan through considering the whitespace and comma
for(int num : line) {
// Do your job
}
}