i really need help on this
Lets says the input is parameter - 2,2,2,2
How can i assign the value for every parameter
1st parameter is 2 so the value assign will be 0 and 1.
I have an example of code but it is in java and i need to do it in JavaScript
for(int i=0; i<args.length;i++)
{
if(args[i].equals("-i"))
{
String data_str= new String();
//SPECIFY DATA VALUES
if(i+1<args.length)
{
i++;
System.out.println ("Parameter => "+args[i]);
data_str=args[i};
}
//ASSIGN DATA VALUES AUTOMATICALLY TO DATA BY COMMAS
StringTokenizer s = newStringTokenizer (data_str,",")
//COUNT PARAMETER
int p = data_str.replaceAll("[^,]","").length();
p++;//AS AN ARRAY SIZE
data= new int[p];
int k = 0;
while(s.hasMoreTokens())
{
data[k]=Integer.parseInt(s.nextToken());
k++;
}
You can split your input string into array.
"2,2,2,2".split(",")
It will lead you to
["2", "2", "2", "2"]
Then you can do whatever you want with your array of args.
If you need integer value, just parse it
parseInt("2") == 2;
Related
for instance
user is inputting
1 3
3 4
i want to capture them in array1[] and array2[]
I tried below
for(int index = 0; index < count ; index++){
while(!input.next().equals('\n')){
int n = input.nextInt();
if (n > 0 )
//save to two dimentional array 1st index is outer loop
}
}
A Two Dimensional (2D) Array in Java is basically an Array of Arrays. This means that each array within that 2D Array can each be of different lengths if so desired. This can obviously be very handy for many different situations.
Your question appears to be in regards to only two specific lines consisting of only two numerical values in each entered line but the demo runnable code below demonstrates how you can allow the User to create a 2D int[][] array of any size. That would of course be a 2D int[][] array consisting of any number of Rows with each row consisting of any number of Columns.
As you know, arrays contain a fixed size and can not grow dynamically unless you create a new array to replace the old one. The code below solves this problem by using two ArrayList objects which can grow dynamically, one of int[] (ArrayList<int[]>) and another of Integer (ArrayList<Integer>) then converting those ArrayList once all the data has been collected from the User.
Read the comments in code for additional information:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CreateATwoDimensionalINTArrayDemo {
public static void main(String[] args) {
// Scanner object to open stream for Keyboard Input
Scanner userInput = new Scanner(System.in);
// Declare the desired 2D Array to create...
int[][] numbers2DArray;
/* An ArrayList of int[] arrays. Used so that our
2D Array rows of int[] arrays can 'dynamically'
grow as needed. */
ArrayList<int[]> tmp2DArray = new ArrayList<>();
/* Display what is required by the User to input
via the keyboard to the Console Window. Pasting
each entry into each entry prompt can be done
as well if desired. */
System.out.println("You are required to enter lines of numbers where each\n"
+ "number in a line is separated with at least one space.\n"
+ "You can enter as many numbers as you like on each line.\n"
+ "Enter nothing to stop entry and display the 2D Array\n"
+ "you have created:\n");
int lineCounter = 1; // Just used for line entry prompt count.
String line = ""; // Used to hold each each entry by the User.
// Loop used to contiuously recieve numerical line entries from the User.
while (line.isEmpty()) {
// Get the numerical line from User...
System.out.print("Enter line #" + lineCounter + ": --> ");
// Increment the entry prompt count (by one).
lineCounter++;
/* Get User input. Code flow stops here until the
User hits the ENTER key within the Console Window. */
line = userInput.nextLine().trim();
/* If nothing is entered except the ENTER key
then exit this 'while' loop (quit). */
if (line.isEmpty()) {
System.out.println("< End Of Entery! >");
System.out.println();
break;
}
/* Split the values entered in current entry
line into a String[] Array: */
String[] lineElements = line.split("\\s+");
/* ENTRY VALIDATION for the above lineElements[] String Array!
Only keep VALID value elements (elements that are proper Integer
of 'int' type numerical values) from the current User entered
data line. We don't want to deal elements that do not contain all
numerical digits (typo type entry values). */
/* An ArrayList used to 'dynamically' create our inner int[] arrays.
Ultimately, these will be the columnar values for the Rows of our
2D Array. */
ArrayList<Integer> tmpList = new ArrayList<>();
/* Iterate through the lineElemnts[] String array in order to
carry out validation on each array element and to convert
each element into an integer (int) value. */
for (int i = 0; i < lineElements.length; i++) {
/* Make sure there are no commas in the supplied
numerical element (ex: 2,436). Some people have
a habbit of doing this. */
lineElements[i] = lineElements[i].replace(",", "");
/* Is the supplied numerical element indeed a
signed or unsigned INTEGER numerical value? */
if (lineElements[i].matches("-?\\d+")) {
/* Yes it is so parse the string numerical element into
an Long data type Integer so as to ensure it will meet
the required 'int' data type MAX_VALUE and MIN_VALUE
threshold. */
long tmpLong = Long.parseLong(lineElements[i]);
if (tmpLong >= Integer.MIN_VALUE && tmpLong <= Integer.MAX_VALUE) {
/* Meets 'int' type numerical criteria so Cast the value
in tmpLong to 'int' and add to the tmpList ArrayList. */
tmpList.add((int)tmpLong);
}
}
}
//Convert the tmpList Integer ArrayList to an int[] Array
int[] arr = new int[tmpList.size()];
for (int k = 0; k < tmpList.size() ; k++) {
arr[k] = tmpList.get(k);
}
/* Add the int[] array to the tmp2DArray ArrayList. */
tmp2DArray.add(arr);
/* Clear the User line entry so as not to meet
the 'while' loop condition and the User can
enter another line. */
line = "";
}
// ------------------ END OF WHILE LOOP ---------------------
/* Convert the tmp2DArray<int[]> ArrayList to a
the numbers2DArray[][] 2D Array... */
numbers2DArray = new int[tmp2DArray.size()][];
for (int i = 0; i < tmp2DArray.size(); i++) {
numbers2DArray[i] = tmp2DArray.get(i);
}
// Display the 2D Array (if there is something in it to display)...
System.out.println("===================================");
System.out.println("Your 2D Array (numbers2DArray[][]):");
System.out.println("-----------------------------------");
if (numbers2DArray.length == 0) {
System.out.println("- Nothing in 2D Array to display! -");
}
else {
for (int i = 0; i < numbers2DArray.length; i++) {
System.out.println("Array #" + (i+1) + ": --> " + Arrays.toString(numbers2DArray[i]));
}
}
System.out.println("===================================");
}
}
Play with it for a little while.
Note how the numbers2DArray 2D Array is initialized
numbers2DArray = new int[tmp2DArray.size()][];
See how the second dimension doesn't receive a length value. This leaves things open for internal arrays of any length.
About the Regular Expressions used within the code as arguments for both the String#split() and String#matches() methods:
Expression: "\\s+"
Used as an argument for the String#split() method:
String[] lineElements = line.split("\\s+");
Split the string contained with the String variable line on every one (or more_ white-space (\\s+) into a String Array named lineElements.
Expression: "-?\\\\d+"
Used as an argument for the String#matches() method:
if (lineElements[i].matches("-?\\d+")) {
If the string element held in the lineElements String Array at index i optionally contains the negative or minus (-) character (the ? makes the - optional) followed by a string representation of an integer value of 1 or more digits (\\d+) then carry out the code within that if code block.
What i am trying to achieve is, let's say I've these variables below:
String num1 = "blah1";
String num2 = "blah2";
String num3 = "blah3";
String num4 = "blah4";
String num5 = "blah5";
Now i want to create a single string variable which would iterate the all values of string's variable inside loop.
for(int i=0; i<=5; i++){
System.out.println(num+""+i); //I know, this would give me some errors. But i want to make something like this to call all string variables.
}
Here i want to print all the values of string's variable by using loop, How to achieve this?
Help would be appreciated!
This is a use case for an array:
String nums[] = new String[] {
"blah1",
"blah2",
"blah3",
"blah4",
"blah5"
}
And then you can easily iterate through the values (note that you don't need to duplicate the number of elements (5) ):
for(int i=0; i<nums.length; i++) {
System.out.println(nums[i]);
}
More about arrays in the Oracle tutorial.
Alternatively, you may use a List instead of an array.
What you need is an Array - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An Array is a container containing a fixed number of values that are the same type, eg:
String [] nums = new String[5];
The above line creates a array called nums of type String which can hold 5 individual String values (they are initially null).
Another way to declare this would be to use:
String [] alt_nums = {"blah1","blah2","blah3","blah4","blah5"};
This set's each value stored in alt_nums to a specific value as declared in the curly braces.
To iterate through an Array you can use an iterative for loop
for(int i = 0; i < alt_nums.length; i++) {
System.out.println(alt_nums[i]);
}
or you can use an enhanced for loop which does this automatically.
for(String num : alt_nums) {
System.out.println(num);
}
You can also use java 8:
List<String> strings = Arrays.asList("sad", "asdf");
strings.forEach(str -> System.out.println(str));
I have the following String data that contain arraylist of objects data,How can i convert it to arraylist type
String data="[Score{id=1, value='3.5'},
Score{id=2, value='4.5'},
Score{id=3, value='2.0'}]";
I would omit the brackets [] at start by cutting out the first and last character. Then you have to split the String to get all the objects in an array. At the end you have to convert the String objects to the actual Score classes. You can do that by the same principle, using substring and indexOf methods.
In terms of code, this would look something like this:
// the String containing all the objects
String data="[Score{id=1, value='3.5'}, Score{id=2, value='4.5'}, Score{id=3, value='2.0'}]";
// Cutting out the brackets []
data = data.substring(1, data.length - 1);
// Splitting the String to smaller pieces
// like "Score{id=1, value='3.5'}", etc
String[] array = data.split(",");
// Creating the ArrayList, where we will save the scores
List<Score> scores = new ArrayList<Score>();
for(int i=0;i<array.length;i++) {
// Creating the Score instance
Score score = new Score();
// Omitting the brackets {}
int start = array[i].indefOx("{") + 1;
int end = array[i].indefOx("}");
// Cutting out the String inside brackets {}
String temp = array[i].substring(start, end);
// We use the same principles again to get those values inside the brackets {}.
String[] tempArray = temp.split(",");
for(int j=0;j<tempArray.length;j++) {
int start = array[i].indefOx("=") + 1;
temp2 = tempArray[j].substring(start);
if(j == 0) {
score.setId(Integer.valueOf(temp2));
} else {
// To cut out the ''
score.setValue(temp2.substring(1, temp2.length));
}
}
// adding score instance to the list
scores.add(score);
}
I would just point out that you would have to verify I used the right indexes, when I used substring and indexOf. If this String would be without the "Score" substring, you would be able to convert this more easily, because then the String would represent a JSONArray.
I need to get textbox value into array and convert them into integer.
I'm not sure whether should I 1st convert and get into array or get into array and after convert.
Please explain with relevant examples
I've already tied out this code segment. But its wrong according to my knowledge.
String data [] = Integer.parseInt(jTextField1.getText());
String[] stringValues = jTextField1.getText().split("[,]");
int[] numArray= new int[stringValues.length];
for(int i=0; i<numArray.length; i++){
numArray[i]= Integer.parseInt(stringValues[i]);
}
You are trying to assign an single inter to a string array so it will not work.
Because two types are incompatible.
Either you must have an integer array or you can have string array and use string value of the textfield.
e.g.
String []stringData = {jTextField1.getText()};
or
int [] = {Integer.parseInt(jTextField1.getText())};
But since you are using just single value it is better to use an variable rather than an array.
Try this:
String str = "34,56,78,32,45";
String[] parts = str.split(",");
for (int i = 0; i < parts.length; i++)
{
int no=Interger.parse(parts[i]);
//Do your stuff here
}
App reads TextEdit value to String and then converts to ArrayList. But before converting it removes spaces between words in TextEdit. So after converting I get ArrayList size only 1.
So my question is how to get the real size. I am using ArrayList because of its swap() function.
outputStream.setText("");
stream = inputStream.getText().toString().replace(" ", "");
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = Arrays.asList(stream);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
}
stream = inputStream.getText().toString();
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = new ArrayList<String>();
for (String x : stream.split(" ")) arrayList.add(x);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
That is my guess at what you actually wanted to do...
The size and the length are different things.
You try to get the size when you want the length.
Use arrayList[0].length() instead of your arrayList.size().
If you want to parse your String to an Array try:
List<String> arrayList = Arrays.asList(stream.split(","));
(this example expects that your text is a comma separated list)
Arrays.asList() expect an array as paramter not just a String. A String is like an array of String of size 1 thats why your list is always of size 1. If you want to Store the words of your String use :
Arrays.asList(stream.split(" ")); //Don't use replace method anymore