Is it possible in Java to break a String into many individual int variables?
String s = "1,2,3,4,5,6";
Like
int var1 = 1;
int var2 = 2;
int var3 = 3;
and so on.
Thanks
String s = "1,2,3,4,5,6";
String[] vars = s.split(",");
int [] varIn= new int[vars.lenght]
for (int i=0;i<vars.lenght;i++)
{
varIn[i]= Integer.parseInt(vars[i]);
}
.
==> varIn[0]=1;
varIn[1]=2;
etc..
split() method is more apt one.One of the other way is use StringTokenizer class, as follows
String abc = "1,2,3,4";
int i = 0;
StringTokenizer st = new StringTokenizer(abc,",");
int array[] = new int[st.countTokens()];
while (st.hasMoreTokens()) {
array[i] = Integer.parseInt(st.nextToken().toString());
i++;
}
I know your problem is already solved.But this code snippet is just to introduce use of StringTokenizer
You cannot dynamically allocate the values to each variable unless you use reflection.
What you can do is split the string on the commas, convert each token into an integer and put these values inside a collection.
For example:
int[] result;
String s = "1,2,3,4,5,6";
String[] tokens = s.split(",");
result = new int[tokens.length];
for(int i = 0; i < tokens.length; i++){
result[i] = Integer.parseInt(tokens[i]);
}
Now you can access each value in the result array (perhaps by assigning var1 to result[1]).
As said: you can also add it to the variables directly using reflection but that's usually a sign that your design went wrong somewhere.
Related
I've tried creating many variations, I tried switching the nested for loops and I tried storing it in a temp value but to know avail, this is a test code of my original code that will invoke multiple methods and I dont want it to get overwritten
public class Main {
public static void main(String[] args) {
char[] memoryArray = new char[24];
String s = new String("hello");
int start = 0;
int length = s.length();
String d = new String("world");
int length1 = d.length();
char tmp;
for (int i = start; i < length - start; i++) {
if (memoryArray[i] == '\u0000') {
memoryArray[i] = s.charAt(i);
}
}
start = start + length;
for (int i = 0; i < length1; i++) {
tmp = d.charAt(i);
for (int j = start; j < start + length1; j++)
if (memoryArray[j] == '\u0000') {
memoryArray[j] = tmp;
}
}
System.out.println(memoryArray);
}
}
expected output helloworld
In your particular case you know what the two strings are, hello and world, but what if you didn't know what strings those variables will hold?
The easiest solution to create the array would be to:
Concatenate the strings together into a new String variable;
Declare the memoryArray and place each character within the new concatenated string into that array;
Display the contents of memoryArray.
With this in mind:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare memoryArray and fill with the characters from newString.
char[] memoryArray = newString.toCharArray();
// Display the Array contents
System.out.println(memoryArray);
But if you want to utilize a for loop for this sort of thing then these steps can do the trick:
Concatenate the strings together into a newString String variable;
Declare the memoryArray and initialize it based on the newString length;
Create a for loop to iterate through the newString one character at a time;
Within the loop, add each character to the memoryArray character array;
Display the contents of memoryArray.
With this in mind:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare and initialize the memoryArray array based on the length of newString.
char[] memoryArray = new char[newString.length()];
// Iterate through newString and fill memoryArray
for (int i = 0; i < newString.length(); i++) {
memoryArray[i] = newString.charAt(i);
}
// Display the Array contents
System.out.println(memoryArray);
i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);
Hi getting an error and don't know why. Here my code for a challenge.
public class Solution {
static void displayPathtoPrincess(int n, String [] grid){
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}
int[] x;
x = new int[m-1];
x[0] = 0;
String p;
String single[];
single = new String[(m*m)];
for(int i = 0; i < (m); i++){
for(int b = 0; b <= m; b++){
single[b] = (grid[i].split("(?!^)"));
System.out.println(p);
}
}
displayPathtoPrincess(m,grid);
}
}
The code is not neat or anywhere near complete but when I run it I get this error:
Solution.java:29: error: incompatible types
single[b] = (grid[i].split("(?!^)"));
^
required: String
found: String[]
1 error
I then tried using a regular string thats not an array didnt work. I then tried to just put in a string where grid[i] is and that also didnt work. Im stuck any help is appreciated!
The split() method returns an array String[] and you are trying to insert array into String.
Just edit your code to this :
String single[][];
single = new String[(m * m)][];
for (int i = 0; i < (m); i++) {
for (int b = 0; b <= m; b++) {
single[i*m+b] = (grid[i].split("(?!^)"));
System.out.println(p);
}
}
displayPathtoPrincess(m, grid);
The error is because the split() method returns a String array String[]. But you are trying to assign it to a String single[b].
Edit: single[b] is not an array. It's just a regular string. single is an array.
String split method returns an array and you cannot assign an array to string :
single[b] = (grid[i].split("(?!^)"));
hence the error. Probably you need to define single as two dimensional array and use it accordingly.
Here is what you were intending to do:
String[] single = grid[i].split("(?!^)");
When you make the call to String.split() Java will return an already allocated String[] array.
Unfortunately, you never finished your code so we are limited from helping you much more than this.
I am trying to create an array that reads string tokens from standard input, and places them in an array, and then prints the words out, until it reaches a specific word. For example, let's say I wanted my array to read a series of words until it reached the word "okay" from std in, print out each word, and then terminate before printing out "okay". The length of this array will be unknown, so I am confused on how to do this.
String s = sc.next();
String[] copy = new String[???];
for( int i = 0; i < copy.length; i++ ){
copy[i] = sc.next();
}
Something like:
String s = sc.next();
ArrayList<String> copy = new ArrayList<String>();
while(!s.equals("okay")){
copy.add(s);
s = sc.next();
}
for (String n : copy){
System.out.println(n);
}
If you don't want to use any list at all, then this becomes impossible. This is simply because array size needs to be defined at the time the array object is created.
So with this constraint you can have a large integer and declare an array of that size.
Final int MY_LARGE_CONST = 3000;
...
String[] tokens = new String[MY_LARGE_CONST]...
This is wasteful since it takes more memory and will fail if you have more tokens than the constant.
Alternaely if you are ok with lists and not ok with iterating over that for actual processing, then u can put the tokens in an ArrayList and once they are all collected, call the toArray method on the ArrayList object.
It's my code Without using ArrayList.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Sample {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
int len = st.countTokens();
String[] array = new String[len];
for (int idx = 0; idx < len; idx++) {
array[idx] = st.nextToken();
}
for (String str: array) {
System.out.println(str);
}
}
}
I have a variable of type StringBuffer which has certain numbers in it say,
StringBuffer newString = new StringBuffer("25 75 25");
Now if I want to separate this out in an integer array, how could i do it?
for(int i=0;i<numberOfItemsInTheStore;i++){
newString.append(values.charAt(0));
values.deleteCharAt(0);
char c = values.charAt(0);
if(c==' ' || values.length()==1){
values.deleteCharAt(0);
value[i] = Integer.parseInt(newString.toString());
newString.delete(0, newString.length());
System.out.println(value[i]);
}
}
What might be wrong in the program?
String[] splits = newString.toString().split(" ");
int[] arrInt = new int[splits.length];
int idx = 0;
for (String s: splits){
arrInt[idx++] = Integer.parseInt(s);
}
You can get String array easily and when you want to use elements as int values use Integer.parseInt() method
StringBuffer newString = new StringBuffer("25 75 25");
String [] strArr = newString.toString().split(" ");
System.out.println(Arrays.toString(strArr));