I have space separated integers in one line and want to input them using BufferedReader. ** There may be more than one spaces between the integers. There may be leading and trailing spaces**
Right now I have following code ,
`
int[] a = new int[1000001]; // integer array
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n; // no of integers
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" "); //taking input
for(int i=1;i<=n;++i)
{
a[i] = Integer.parseInt(s[i]);
}
`
Its not working.Please help. Any help or suggestion would be appreciated . Thanks.
Edit:1 - I used split("\s+"). But this cares for more than one spaces between integers... What about leading and trailing spaces..?? How to deal with them..?
Use split("\\s+") it should do the trick. It tells split() to use one or more space characters as a delimiter between two tokens.
Also you should allocate you int[] after you have read the number of int to read instead of allocating one that is way too big, you waste memory for nothing
You can first read the line, then use a regex to replace all whitespace with only one space. Then you can split it as you do above. Let me know if you need further help or code examples.
Edit: the NumberFormatException could be because the Integer.parseInt is trying to parse something outside of the value of an integer. Try Long.parseLong instead.
Related
How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.
I have been trying to take the array input by separating the values with '#'.Can anyone of you help me to get through this?
I have used the split function but it is not working. Is there any possibility of solving this problem?
Take your and start appending it to String then:
StringBuffer str;
//loop it
str.append(arr[i])
String[] arrOfStr = str.split("#");
After that convert to Integer and use
I am trying to split a word into its individual letters.
I tried both String.split("") and String.split("|") however when I split a word it is creating a extra empty element.
Example:
word = "word";
int n = word.length();
Log.i("20",Integer.toString(n));
String[] letters = word.split("|");
Log.i("25",Integer.toString(letters.length));
The output in the Android Monitor is:
07-21 15:50:23.084 5711-5711/com.strizhevskiy.movetester I/20: 4
07-21 15:50:23.085 5711-5711/com.strizhevskiy.movetester I/25: 5
I put the individual letters into TextView blocks and I can actually see an extra empty TextView.
When I test these methods in my regular Java it outputs the expected answer: 4.
I am almost tempted to think this is an actual bug in Android's implementation of the method.
I am thinking you want to do this:
public Character[] toCharacterArray( String s ) {
if ( s == null ) {
return null;
}
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
Instead of splitting a word without delimiters?
I hope this helps!
It's hard to say if it's bug or expected behavior, because what are you doing doesn't make sense. You are trying to split string with logical OR (split is waiting for Regular expression, not just a string), so as result it could be different result in Android comparing with normal java, and I don't see there any issue.
Anyway, there is many ways to achieve what you want in a normal way, e.g. just iterating over word by each char in a cycle or just use toCharArray String's method.
Thank you for the suggestions. My current work-around is to use a mock array and copying over into a fresh array using System.arraycopy().
String[] mockLetters = word.split("");
int n = word.length();
String[] letters = new String[n];
System.arraycopy(mockLetters,1,letters,0,n);
I appreciate the suggestions to use toCharArray(). However, these letters then get put into TextViews and TextView doesnt seem to accept char. I could, of coarse, make it work but I've decided to stick with what I currently have.
Tom, in a comment to my question, answered my underlying issue:
Why String.split() worked differently in Android than it does in Java?
Apparently the rules for String.split() changed with Java 8.
Try passing a 0 as the limit per the documentation below so that the trailing spaces are discarded.
String[] split (String regex,
int limit)
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
I use the following code each time I need an integer array:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int[] a =new int[str.length];
int j = 0;
for(String i : str)
a[j++]=Integer.parseInt(i);
I use BufferedReader instead of Scanner to reduce the time complexity during input. However I wonder whether this method is efficient than Scanner when the array size is relatively larger(>100). In such cases, is there a better way to convert a String array to an integer array ?
With java 8, it's pretty straightforward, and only one line:
int[] a = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
In my experience StringTokenizer performs better than calling split. After that I convert the tokens into ints the same way you do. I think this is the best performing method to input a series of many integers printed on a single line. Here is a thread where different approaches are discussed and measured.
Also I would like to point out that this is the approach used by most programming competitors such as the legend Petr Mitrichev, thus I believe it is as good as you can get.
Short story: I generate random numbers and end symbol 0-9/ ( '/' is line end symbol, if I meet it, I go to write to next line in file.) When I generated my numbers and put in file, I want to get back those numbers from file but in not like strings, it should be Integers.
Assume my file looks like this:
846525451454341*
*
0067617354809629733035*
3313449117867514*
02337436891267261671546*
469980603887044*
7*
9*
642*
*
0617044835719095066*
5*
7175887168189821760*
581*
76300152922692817*
As you can noticed, line is able to hold only '*' in some cases (As I said it is generated random).
My purpose
I want to get back these lines like integers. For example I take 1 line until I meet end symbol ( '/' ) then I loop another line and so on.
Some snippet:
public void readGeneratedFile() throws IOException {
try(BufferedReader r= new BufferedReader(new FileReader("C:\\java\\numbers.txt"))){
int ch;
s = new String();
while((ch=r.read())!=-1){
s+=String.valueOf(Character.toChars(ch)).replace(" ",""); // Here I take all file into String, But this approach is leading to boilerplate code;
}
// catch IOException , finally close the file.
My question
How can I get back those lines like integers? (Suppose I want to take some actions with those numbers) It's cool if you get an idea what I want to do.
Thanks.
EDITED:
Sorry for misunderstanding, It is not what I want. I want to get back separated values, For example I have 123456/564654/21 string, and my Integer array[1][index] should looks like 1,2,3,4,5,6 then I meet end line symbol '/' I jump to array[2][index] and fill it with next line in file.
You can try like this. also.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
BigInteger integer;
while (line != null) {
line = line.replace("*","");
integer = new BigInteger(line);
//Your stuf
line = br.readLine();
}
} finally {
br.close();
}
Your Strings are crossing the integer limit , You need BigInteger
Ex
BigInteger b = new BigInteger("7175887168189821760");
And you cannot get it back like integers since they are crossing the limit.
Use a StringBuilder as char accumulator (StringBuilder.append()) and finally
int result = Integer.parseInt(builder.toString());
This will help
Integer.parseInt(String)
Since you have bigger values greater than what an Integer can store, you can go for
Long.parseLong(String)
The other way is to use BigInteger(String) for working on the big numbers