• Log in or sign up for an account here: https://www.sythe.org/login

Seperating items within a string

DtheK

Apprentice

Banned
Joined
Oct 17, 2009
Sythe Gold
0
Messages
873
Hi,

I just wanted to know if there was a way to seperate items within a string, say, with a space in between each different input.

For example,

in the string "16 15" if I wanted to store 16 in one variable and 15 in another how would I go about doing this
 
Create two different fields?
Or an array?
Or a collection?

You'll need to provide some code for the most effective way to do this.
 
Okay, here's some sample code:

import javax.swing.JOptionPane;
public class test
{
public static void main(String[] args)
{
String s = JOptionPane.showInputDialog("Enter the data with a space in between each number");
}
}


Say I put "1 2 3 4" as the input and wanted to store 1 in variable a, 2 in variable b, etc.
 
Okay, here's some sample code:

import javax.swing.JOptionPane;
public class test
{
public static void main(String[] args)
{
String s = JOptionPane.showInputDialog("Enter the data with a space in between each number");
}
}


Say I put "1 2 3 4" as the input and wanted to store 1 in variable a, 2 in variable b, etc.
Then use the split() method, as SuF stated.
 
<3 n4n0
Discord Verified
Two Factor Authentication User
Community Participant
Spam Forum Participant
Sythe's 10th Anniversary
Sythe Awards 2011 Winner
^That would store the input in a string array. Then you have to cast it to int or float or what ever and make sure it all works and discard any input that doesn't...
 
^That would store the input in a string array. Then you have to cast it to int or float or what ever and make sure it all works and discard any input that doesn't...
Cast the java.lang.String[] or a primitive type? >_<

I'm sure what you meant was, that you need to get a single java.lang.String element of the array, and call the corresponding method of the corresponding wrapper class to get a primitive type from the String (Object's cannot be cast to primitive types, as primitive types are not Objects).

In pseudo-code
Code:
String input = JOptionPane.showInputDialog(...);
if(input != null) {
    String[] data = input.split(" ");
    for(String s : data) {
        try {
            int i = Integer.parseInt(s);
            //Do whatever you need with the input
        } catch (RuntimeException e) { //I cbf to lookup the actual name
            //Execption-handling code here
        }
    }
}
 
<3 n4n0
Discord Verified
Two Factor Authentication User
Community Participant
Spam Forum Participant
Sythe's 10th Anniversary
Sythe Awards 2011 Winner
^Basically what I ment.
 
Runescape Gamblingrunescape gambling
Back
Top