I have a string that I want to split with a certain delimiter
private int [] mMaxValues;
public void setMaximum(String maximum) {
mMaxValues = splitByDelimiter(maximum, ":");
}
But the splitByDelimiter method return a string array into an int array
public String[] splitByDelimiter(String list,String delimiter) {
String[] items = list.split("\\" + delimiter);
for (String s : items) {
s.trim();
}
return items;
}
What is the best way to fix this problem? I'm guessing that iterating the string array and casting them to integers isn't the best solution.
I could also create a new splitByDelimiter that returns an int array but I'm guessing there is a better solution than that..
Is this a situation where you could use generics (I don't have a lot of experience with generics)?
Thx :)
You need to convert string array to int array explicitly. Use:
public void setMaximum(String maximum) {
Strin[] array = splitByDelimiter(maximum, ":");
int i = 0;
mMaxValues = new int[array.length];
for (String value : array) {
mMaxValues[i] = Integer.parseInt(value);
i++;
}
}
Also you need to handle few cases which may cause NullPointerException :
maximum is null
array is null
NumberFormatException may be raised while parsing Integer.parseInt(value), handle it.
Loop over the string array and store them in an int array.
String input = ...;
String[] parts = input.split(':');
int[] result = new int[parts.length];
for (int n = 0; n < parts.length; ++n)
{
result[n] = Integer.parseInt(parts[n]);
}
return result
Related
public int[] findWord(String text, String word) throws NullPointerException {
// my code must be here
return ;
}
}
To get the index of the word in the text:
text.indexOf(word);
You can add this value to the array
create ArrayList<Integer> arrayList = new ArrayList<>();, then add elements to it by method arrayList.add(int element), and then cast AL to array: int[] result = arrayList.toArray(new int[arrayList.size()]);
add() - adds elements to the end of ArrayList
I did it!
public int[] findWord(String text, String word) throws NullPointerException
{
int[] first = new int[text.length()];
int j=0;
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1;j++) {
first[j]=i;
}
int[] second = new int[j];
second = Arrays.copyOf(first,j);
return second;
}
public int[] findWord(String text, String word) throws NullPointerException
{
int[] first = new int[text.length()];
int j=0;
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1;) {
System.out.println(i);
}
return first;
}
Here is my try, How can I add (i) to my array? It's just printing exactly needed numbers.
I am having a String like this "5006,3030,8080-8083".
I want each element separately from the String:
5006
3030
8080
8081
8082
8083
Here's my code:
int i=0,j=0;
String delim = "[,]";
String hyphon = "[-]";
String example = "5006,3030,8080-8083";
String p[] = example.split(delim);
int len = p.length;
for(i=0;i<len;i++) {
String ps[]=p[i].split(hyphon);
if(ps.length>1) {
int start = Integer.parseInt(ps[0]);
int finish = Integer.parseInt(ps[1]);
int diff = finish-start+1;
for(j=0;j<diff;j++) {
System.out.println(start+j);
}
} else if(ps.length==1) {
System.out.println(ps[0]);
}
}
Is there any better solution or any class that simplifies my code?
I also want the numbers in a ascending order.
Try this code :
public static void main(String[] args) {
String input = "5006,3030,8080-8083";
List<Integer> list = new ArrayList<Integer>();
String[] numbers = input.split(",");
for (String s : numbers) {
if (s.contains("-")) {
String[] range = s.split("-");
int from = Integer.parseInt(range[0]);
int to = Integer.parseInt(range[1]);
for (int i = from; i <= to; i++) {
list.add(i);
}
}
else {
list.add(Integer.parseInt(s));
}
}
System.out.println("in asc order");
Collections.sort(list);
System.out.println(list.toString());
System.out.println("in desc order");
Collections.reverse(list);
System.out.println(list.toString());
}
My output :
in asc order
[3030, 5006, 8080, 8081, 8082, 8083]
in desc order
[8083, 8082, 8081, 8080, 5006, 3030]
I also want the numbers in a ascending order.
This adds an unexpected twist to your whole program, because once you realize that printing-as-you-go no longer works, you need to start almost from scratch.
The first thing to do is picking an appropriate representation. It appears that you represent ranges of integers, so start by defining a class for them:
class IntRange : Comparable<IntRange> {
private int low, high;
public int getLow() {return low;}
public int getHigh() {return high;}
public IntRange(int low, int high) {
// Add range check to see if low <= high
this.low = low; this.high = high;
}
public IntRange(int point) {low = high = point;}
#Override
public void print() {
for (int i = low ; i <= high ; i++) {
System.out.println(i);
}
}
#Override
public int compareTo(IntRange other) {
...
}
}
Now you can use your code to split on [,], then split on [-], construct IntRange, and put it into an ArrayList<IntRange>. After that you can use sort() method to sort the ranges, and print them in the desired order.
But wait, there is more to your problem than meets the eye. Think what would happen for input like this:
1,5,3-7,6
Where should 5 and 6 be printed? It is not good to print it before or after 3-7, so the trick is to remove points inside ranges.
But even that's not all: what do you do about this input?
1-5,3-7
You should print numbers 1 through 7, inclusive, but this would require merging two ranges. There is a good data structure for doing this efficiently. It is called a range tree. If your input is expected to be large, you should consider using range tree representation.
You are good to go; you can minimize the counter variables using enhanced for loop and while loop.
String example = "5006,3030,8080-8083";
String[] parts=example.split(",")
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(String part: parts)
{
if(part.contains("-"))
{
String subParts[]=part.split("-");
int start = Integer.parseInt(subParts[0]);
int finish = Integer.parseInt(subParts[1]);
while(start <= finish)
{
numbers.add(start);
System.out.println(start++);
}
}
else {
System.out.println(part);
numbers.add(Integer.parseInt(part));
}
}
Integer[] sortedNumbers = new Integer[numbers.size()];
sortedNumbers = Arrays.sort(numbers.toArray(sortedNumbers));
Update (from comment):
Numbers are sorted now.
Try this
String str = "5006,3030,8080-8083";
String[] array = str.split(",");
String ans = "";
for(int i = 0; i < array.length; i++){
if(array[i].contains("-")){
String[] array2 = array[i].split("-");
int start = Integer.parseInt(array2[0]);
int end = Integer.parseInt(array2[array2.length - 1]);
for(int j = start; j <= end; j++){
ans = ans + j + ",";
}
}
else{
ans = ans + array[i] + ",";
}
}
System.out.print(ans);
This code assumes all integers are positive.
public static void main(String[] args) {
String testValue="5006,3030,8080-8083";
Integer[]result=parseElements(testValue);
for (Integer i:result){
System.out.println(i);
}
}
/**
* NumberList is a string of comma-separated elements that are either integers, or a range of integers of the form a-b.
* #param numberList
* #return all the integers in the list, and in ranges in the list, in a sorted list
*/
private static Integer[] parseElements(String integerList) {
ArrayList<Integer> integers=new ArrayList<Integer>();
String[] csvs=integerList.split(",");
for(String csv : csvs){
if(csv.contains("-")){
String[] range=csv.split("-");
Integer left=Integer.decode(range[0]);
Integer right=Integer.decode(range[1]);
for(Integer i=left;i<=right;i++){
integers.add(i);
}
} else {
integers.add(Integer.decode(csv));
}
}
Collections.sort(integers);
return integers.toArray(new Integer[0]);
}
Using Guava's functional idioms you can achive this declaratively, avoiding the verbose, imperative for-loops. First declare a tokenizing function which converts each token in the comma-delimited string into an Iterable<Integer>:
private static final Function<String, Iterable<Integer>> TOKENIZER =
new Function<String, Iterable<Integer>>() {
/**
* Converts each token (e.g. "5006" or "8060-8083") in the input string
* into an Iterable<Integer>; either a ContiguousSet or a List with a
* single element
*/
#Override
public Iterable<Integer> apply(String token) {
if (token.contains("-")) {
String[] range = token.trim().split("-");
return ContiguousSet.create(
Range.closed(Integer.parseInt(range[0]),
Integer.parseInt(range[1])),
DiscreteDomain.integers());
} else {
return Arrays.asList(Integer.parseInt(token.trim()));
}
}
};
then apply the function to the input:
String input = "5006,3030,8080-8083";
Iterable<String> tokens = Splitter.on(',').trimResults().split(input);
SortedSet<Integer> numbers = Sets.newTreeSet();
Iterables.addAll(numbers,
// concat flattens the Iterable<Iterable<Integer>>
// into an Iterable<Integer>
Iterables.concat(Iterables.transform(tokens, TOKENIZER)));
As all of the logic is basically coded into the Function, the client code only needs to tokenize the string into an Iterable<String> (with Splitter), apply the Function through Iterables.transform, flatten the result of the transformation using Iterables.concat and finally add the resulting Iterable<Integer> into a SortedSet<Integer> which keeps the numbers in ascending order.
with java 8 stream api :
public static void main(String[] args) {
String s = "5006,3030,8080-8083";
Arrays.stream(s.split(","))
.flatMap(el -> el.contains("-") ? rangeToStream(el) : Stream.of(Integer.valueOf(el)))
.sorted()
.forEachOrdered(e -> System.out.println(e));
}
private static Stream<? extends Integer> rangeToStream(String el) {
AtomicInteger[] bounds = Arrays.stream(el.split("-")).map(e -> new AtomicInteger(Integer.parseInt(e))).toArray(size -> new AtomicInteger[2]);
return Arrays.stream(new Integer[bounds[1].get() - bounds[0].get() + 1]).map(e -> bounds[0].getAndIncrement());
}
U can code something like this -
String s="5006,3030,8080-8083";
String s2[]=s.split(",");
List<Integer> li= new ArrayList<Integer>();
List<Integer> numbers= new ArrayList<Integer>();
for(int i=0;i<s2.length;i++){
if(s2[i].contains("-")){
li.add(i);
}
else{
numbers.add(Integer.parseInt(s2[i]));
}
}
for(Integer i:li){
String str=s2[i];
String strArr[]=str.split("-");
for(int j=Integer.parseInt(strArr[0]);j<=Integer.parseInt(strArr[1]);j++){
numbers.add(j);
}
}
Collections.sort(numbers);
for(Integer k:numbers){
System.out.println(k);
}
public static void main(String[] args)
{
String example = "5006,3030,8080-8083";
String[] splitString = example.split(",");
List<Integer> soretedNumbers = new ArrayList<>();
for(String str : splitString)
{
String[] split2 = str.split("-");
if(split2.length == 1)
{
soretedNumbers.add(Integer.parseInt(str));
}
else
{
int num1 = Integer.parseInt(split2[0]);
int num2 = Integer.parseInt(split2[1]);
for(int i = num1;i <= num2; i++)
{
soretedNumbers.add(i);
}
}
}
Collections.sort(soretedNumbers);
for(int i : soretedNumbers)
{
System.out.println(i);
}
}
I have 2 string arrays.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
I'd like the result of my merge() method to concatenate each element from the first array with the respective element of the second array separated by a comma.
Below is my code
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
This does not work. What's wrong with my code?
What's wrong is that you are looping over expectationsList and breaking out of the loop after the first iteration:
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
So the result is that you are always retrieving the first element of expectationsList.
Since what you want is to loop over two arrays, you should use an index:
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
Also, note that this implies that the size of testList is the same as the size of expectationsList. Your method should probably throw an exception if this is not the case.
Note that you do not need to convert the input arrays into lists. You can use them as-is.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 solution:
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
You're iterating through each member of testList and then for each one, iterating through each member of expectationsList. You want to iterate through each of both of them together.
What you want to do is something like this:
private static String[] merge(String[] tests, String[] expectations) {
String[] result = new String[tests.length];
for(int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i];
}
return result;
}
This code makes the assumption that tests and expectations have the same length. You might want to do a check for that at the beginning:
if (tests.length != expectations.length) {
throw new IllegalArgumentException("tests and expectations are of different lengths")
}
Notice how now you're getting the element at the same index from both arrays.
Sidenote: You can iterate over arrays with the for each format. This works just fine:
String[] myStringArray = getStringArray();
for (String myString : myStringArray) {
// Do something
}
You don't need to convert to a List in order to iterate :)
Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}
I'm working on my graphic user interface for a application I'm creating. Basically there is this JTextField that the user has to input integers. For example
25, 50, 80, 90
Now, I have this other class that needs to get those values and put them in an int Array.
I've tried the following.
guiV = dropTheseText.getText().split(",");
And in the other class file I retieve the String, but I have no idea how to get the value for each one.
In the end I'm just trying to get something like
int[] vD = {textfieldvaluessplitbycommahere};
Still fairly new to Java but this has me crazy.
private JTextField txtValues = new JTextField("25, 50, 80, 90");
// Strip the whitespaces using a regex since they will throw errors
// when converting to integers
String values = txtValues.getText().replaceAll("\\s","");
// Get the inserted values of the text field and use the comma as a separator.
// The values will be returned as a string array
private String[] strValues = values.split(",");
// Initialize int array
private int[] intValues = new int[strValues.length()];
// Convert each string value to an integer value and put it into the integer array
for(int i = 0; i < strValues.length(); i++) {
try {
intValues[i] = Integer.parseInt(strValues[i]);
} catch (NumberFormatException nfe) {
// The string does not contain a parsable integer.
}
}
As you are fairly new to Java, rather than giving you the code snippet, I will just give you some indications:
Use the String class: it has a method for splitting a String into an array of Strings.
Then use the Integer class: it has a method to convert a String to an int.
You cant do it directly, you may need to add a method to convert your string array to int array. Something like this:
public int[] convertStringToIntArray(String strArray[]) {
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
Pass your guiV to this method and get back the int array
a simple solution is a function hat does the conversion:
public static int[] convertTextFieldCommaSeparatedIntegerStringToIntArray(String fieldText) {
String[] tmp = fieldText.split(",");
int[] result = new int[tmp.length];
for(int i = 0; i < tmp.length; i++) {
result[i] = Integer.parseInt(tmp[i].trim());
}
return result;
}
The essential methods are:
split for splitting the original input at the comma.
parseInt for converting a String -> int. The valueOf function of Integer is an option but then you have to convert String -> Integer -> int.
Note:
You should use trim to eliminate white-spaces. Furthermore, you should catch the NumberFormatException thrown by parseInt. As an unchecked exception you do not need to catch it, but it is always wise to check user input and sanitize it if necessary.
Try this code:
public int[] getAsIntArray(String str)
{
String[] values = str.getText().split(",");
int[] intValues = new int[values.length];
for(int index = 0; index < values.length; index++)
{
intValues[index] = Integer.parseInt(values[index]);
}
return intValues;
}