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;
}
Related
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 having trouble multiplying the elements of a 2d string array by the element of another.
Heres the code:
public static String updateString(String[][] array, String[] prices)
{
String [][] newArray = new String[array.length][];
for(int row = 0; row < prices.length; row++)
{
if (array[row][0].equals(prices[row]))
{
for(int i = 0; row <array.length; row++)
{
newArray[row][i+1] = array[row][i+1] * prices[i+1];
}
}
}
}
Here are what the files look like:
array:
Omaha,104,1218,418,216,438,618,274,234,510,538,740,540
Saint Louis,72,1006,392,686,626,670,204,286,236,344,394,930
Des Moines,116,1226,476,330,444,464,366,230,602,260,518,692
Chicago,408,948,80,472,626,290,372,282,488,456,376,580
Kansas City,308,1210,450,234,616,414,500,330,486,214,638,586
Austin,500,812,226,470,388,488,512,254,210,388,738,686
Houston,454,1086,430,616,356,534,218,420,494,382,476,846
New Orleans,304,1278,352,598,288,228,532,418,314,496,616,882
prices array:
Omaha,7.5
Saint Louis,10.5
Des Moines,8.5
Chicago,11.5
Kansas City,12.5
Austin,10.75
Houston,12.5
New Orleans,9.25
As you can see, the first column of each array lists the city, so if the cities match up, I need the 1st array's elements multiplied by omaha(7.5).
IF you have no choice but to use Strings where numbers should be the best choice, then try to convert your strings to numbers like this -
String str = "22.43";
try{
double str = Double.parseDouble(str);
}catch(NumberFormatException nfe){
nfe.printStackTrace();
}
This is just an example. You might want to see the disadvantages of using print stack trace -
Why is exception.printStackTrace() considered bad practice?
There are two problems with your inner loop.
1) You need to increment 'i' at some point. You need to have in your loop:
i++;
Currently, you are traversing the rows not the columns in your inner loop, get rid of the:
row++;
2) You never initialize the columns of newArray. Since you are using a static 2D array you should have a max number of columns shown here as MAX_WIDTH.
String [][] newArray = new String[array.length][MAX_WIDTH];
As the others mentioned, you definitely need to convert from String to double before you can do any 'math' on the variables. Here Java automatically casts Double (class) to double (data structure).
try {
double val = Double.parseDouble(string);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Try casting the values to either an integer or double type. Currently you are attempting to multiply string values.
You are multiplying Strings, first convert them to double and then multiply
First you are not returning any thing and also Change your return type from String to String [] [] as you are returning 2d Array
Here is the code
public static String [][]updateString(String[][] array, String[] prices)
{
String [][] newArray = new String[array.length][];
for(int row = 0; row < prices.length; row++)
{
if (array[row][0].equals(prices[row]))
{
for(int i = 0; i<array.length; i++)
{
Double d=Double.parseDouble(array[row][i+1]) * Double.parseDouble(prices[i+1]);
newArray[row][i+1] = d.toString();
}
}
}
return newArray;
}
}
Your inner loop should be something like I have done in the code depending on what you want
I have an Arraylist that I want to convert to a double[] array. I first convert the Arraylist to a String []. I then try to convert the String[] to a double[] but fail in the process. Here's the issue: the string contains some text, as well as some numbers with decimals. I want to convert only the numbers and decimals to a double[] array and simply delete the text. However, I only know how to delete the text with a String, not a String[]. Please take a look:
import java.util.ArrayList;
import java.util.List;
import jsc.independentsamples.SmirnovTest;
public class example {
public static void main(String[] arg) throws Exception {
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
list1.add("RSP0001,1.11,1.22");
list1.add("RSP0002,2.11,2.22");
list1.add("RSP0003,3.11,3.22");
list1.add("RSP0004,4.11,4.22");
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
str1.replaceAll("RSP_\\d+","");
double array1 = Double.parseDouble(str1);
System.out.println(array1);
}
}
Two errors come from this: the first is a "cannot find symbol" error at str1.replaceAll. The second is a "method parseDouble" error at "Double.parseDouble". The issue there is I need a String instead of a String[].
Any ideas on how to convert my String[] to a double[] ?
Thanks,
kjm
You need to split each String in list1 on "," and attempt to parse each String that gets split out:
ArrayList<Double[]> results = Lists.newArrayList();
for( String s : list1 ) {
String[] splitStrings = s.split(",");
Double[] doublesForCurrentString = new Double[splitStrings.length];
for(int i=0; i<splitStrings.length; i++){
try {
doublesForCurrentString[i] = Double.valueOf(splitStrings[i]);
} catch( NumberFormatException ex ) {
// No action.
}
}
results.add(doublesForCurrentString);
}
Double[][] doubleArray = (Double[][])results.toArray();
Crucial points:
EDIT: As #Tim Herold points out, you're probably better of performance-wise avoiding attempting to parse content you know to be non-numeric. In this case, I'd still split first and then just put in code that prevents you from attempting to parseDouble() on the first split String in each line, rather than trying to do String replacement before the split; that will be faster (and if we're not concerned about performance, then try/catch is perfectly fine and more readable). ORIGINAL: You need a try/catch when you try to parse the doubles, in case there's any invalid input. Bonus: you don't need to remove the non-numeric text now, you can just let this try/catch handle it.
Your strings have two doubles in each of them. You're not going to be able to just strip the text at the beginning and then parse the rest, because it's not going to be a valid double.
ArrayLists are generally easier to use; I'd opt for returning ArrayList<Double> (or ArrayList<ArrayList<Double>>) over Double[] or Double[][] any day of the week. There are certainly situations where I'd do differently, but yours doesn't sound like one of them to me.
Loop throug the Array:
foreach String[]
double[counter] = parseToDouble(String[counter])
EDIT:
Java:
String[] str1 = list1.toArray(str1);
double[] dou1 = new double[str1.length]
for(int counter = 0; counter < str1.length;counter++)
dou1[counter] = Double.parseDouble(str1[counter].replaceAll("RSP_\\d+",""));
Use this
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
double[] doubleArray = new double[str1.length]
int i=0;
for(String s:str1){
doubleArray[i] = Double.valueOf(s.trim());
i++;
}
This will do the work.
double[] doubles = new double[array1.length];
for(int i=0; i<array1.length; i++){
doubles[i] = Double.valueOf(array1[i])
}
Thanks SmartLemon for the edit, you could do this too instead of using a String[]:
double[] doubles = new double[list1.size()];
for(int i=0; i<list1.size(); i++){
doubles[i] = Double.valueOf(list1.get(i).replace("RSP_\\d+",""));
}
EDIT: So yes, you need a delimiter:
double[] doubles = new double[array1.length*2]; //multiply by 2 because you really have 8 numbers not 4
String [] array2 = null;
for(String string: array1) {
array2 = string.split(",");
for(int i=0; i<array2.length; i++){
doubles[i] = Double.valueOf(array2[i]);
}
}
this should do the work for sure.
I would do this:
make array
convert to string
then this code
for (String s: list1) {
boolean obtained = false;
double tempD;
try {
tempD = Double.parseDouble(s);
obtained = true;
} catch (Exception e) {
e.printStackTrace();
}
if (obtained) {
list2.add(tempD);
}
}
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
i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]