String Qty1 = "1";
String Qty2 = "2";
String qtyString = "", bString = "", cString = "";
for(int j = 1; j <= 2; j++)
{
qtyString = String.valueOf(("Qty" + j));
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = Qty1;
qtyString = Qty2;
I would like to get qtyString = 1, qtyString = 2; I want to print Qty1 and Qty2 value in my for loop. In C#, this code works correctly. I don't know how to get qtyString value as 1, 2 in java.
You should use array of strings for this purpose.
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
String array is needed if you want to print a list of string:
String[] Qty = {"1", "2"};
String qtyString = null;
for (int j = 0; i<=1; j++) {
qtyString = Qty[j];
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = 1
qtyString = 2
I don't know for sure what you're trying to do, and you've declared Qty1 twice in your code. Assuming the second one is supposed to be Qty2, then it looks like you're trying to use string operations to construct a variable name, and get the value of the variable that way.
You cannot do that in Java. I'm not a C# expert, but I don't think you can do it in C# either (whatever you did that made you say "it works in C#" was most certainly something very different). In both those languages and in all other compiled languages, the compiler has to know, at compile time, what variable you're trying to access. You can't do it at runtime. (Technically, in Java and C#, there are ways to do it using reflection, depending on how and where your variables are declared. But you do not want to solve your problem that way.)
You'll need to learn about maps. Instead of separate variables, declare a Map<String, String> that maps the name that you want to associate with a value (Qty1, Qty2) with the value (which is also a String in this case, but could be anything else). See this tutorial for more information. Your code will look something like
Map<String, String> values = new HashMap<>();
values.put("Qty1", "1");
values.put("Qty2", "2");
...
qtyString = values.get("Qty"+j);
(Actually, since your variable name is based on an integer, an array or ArrayList would work perfectly well too. Using maps is a more general solution that works in other cases where you want names based on something else beside sequential integers.)
Try this examples:
With enhanced for-loop and inline array:
for(String qty : new String[]{"1", "2"})
System.out.printf("qtyString = %s\n", qty);
With enhanced for-loop and array:
String [] qtys = {"1", "2"};
for(String qty : qtys)
System.out.printf("qtyString = %s\n", qty);
Using for-loop and array:
String [] qty = {"1", "2"};
for(int i = 0; qty.length > i; i ++)
System.out.printf("qtyString = %s\n", qty[i]);
you can try this for java:
static String Qty[] = {"1", "2"} ;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
}
And For Android:
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
Related
I have a text string that I receive from PL/SQL. I need to convert each object that is separated by a ';'.
This is my string enter image description here
I need to get that information and create the objects that come in that string.
//all objects come in a single text string
first object is 830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;
second object is 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS;
third object is 800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000;
fourth object is 900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;
Example:
Class MyClass{
Integer number;
String text;
Integer number2;
String text;
}
List<MyClass> myList = new ArrayList<>();
myClass.SetNumber(830114921-1);
myClass.SetText("TIGO");
myClass.SetNumber2(13);
myClass.SetText2("RECARGA CELULAR TIGO");
myList.add(myClass);
//I can split the 4 objects but if more objects come in the text string, can //no longer be.
String str = "830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;"
+ " 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS; "
+ "800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000; "
+ "900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;";
String[] arrOfStr = str.split(";", 4);
List<String> list = new ArrayList<>();
for (String a : arrOfStr) {
list.add(a);
}
for (String data : list) {
String result2 = data.replaceAll("\\<,>", " ");
System.out.println(result2);
}
You can count how many ; exits in the String and then use str.split()
...
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ';') {
count++;
}
}
String[] arrOfStr = str.split(";", count);// instead of 4
...
This will solve you problem but there are better ways to do it, using a regular expression . Learn more here
Edit :
You also need to do the same thing to every attribute of your object but the counting is a little bit different :
...
count = 0;
for (int i = 1; i < arrOfStr[0].length()-1; i++) {
if (arrOfStr.charAt(i-1) == '<'arrOfStr.charAt(i) == ',' && arrOfStr.charAt(i+1) == '>') {
count++;
}
}
List<String> listOfObjectsFromSQL = new ArrayList<MyClass>();
String[] attributes = new String[count];
for (String strObj : arrOfStr) {
attributes = strObj.split("<,>", count);
//create you object
MyClass obj = new MyClass();
//fill your object with values from the query
obj.setNumber(attributes[0]);
obj.setText(attributes[1]);
obj.setNumber2(attributes[2]);
obj.setText2(attributes[3]);
//add them to your list to use them...
listOfObjectsFromSQL.add(obj);
}
...
The data is split with <,> and ; so you should easily be able to split the string and collect the data. Java has a String.split() method. First split the string object that contains all the data into an array of strings by splitting on ; and then loop over these and split them on <,>.
At this point you should be able to set your attributes according to the order of the data in the string (assuming these are ordered properly).
I'm new to programming in Java so I'd like some help on this matter, thank you very much for your time :)
I want to check if "CheckAutonomy" is contained in a substring using indexOf and a for iterator to iterate trough my objects,(ambient contains 4 objects everytime, this is the "wouldbe" code :
ReEdit: I added more details, i hope this will be enough , i really don't know how to grasp it :|
public static void scrivi(JSONArray jsa, String nome, String versione ) throws IOException{
for(int j = 0; j < jsa.length(); j++){
JSONArray endpoint = jsa.getJSONArray(j);
bsrURI = getObjectValueFromJSONArrayEndpointData(endpoint, "bsrURI");
String query = normalizeQuery(QUERY_GET_BSRURI, null, null, null, bsrURI);
JSONArray jsaUriBSR = queryExecutor(query);
/*???
for(i = o; i < 3; i++){
if (ambient.contains("CheckAutonomy")){
}
}
???*/
String ambient = jsaUriBSR.get(0).toString()
.substring( jsaUriBSR.get(0).toString().indexOf('#') + 1, jsaUriBSR.get(0).toString().length() - 2 );
System.out.println(ambient);
}*/
String line = ambient + ";\n";
bw.write(line);
}
}
Solved it with something like this:
for(int i = 0; i < result.length(); i++){
if (risultato.get(i).toString().contains("CheckAutonomy"))
ambient = result.get(i).toString()
.substring( result.get(i).toString().indexOf('#') + 1,
result.get(i).toString().length() - 2 );
}
Nevertheless, thank you for your time ! :P
I want to format log like this:
"order with orderid=1,orderid=2,orderid=3,orderid=4"
I have array with values [1,2,3,4].
I understand that it is enough easy to use loop for this but I want to know if there is tool in jdk (or library) which can do this.
Using java 8:
int[] n = new int[]{1,2,3,4};
String orders = Arrays.stream(n).mapToObj(i -> "orderid=" + i).collect(Collectors.joining(","));
String result = "order with " + orders;
You can easily build such a String using for-loop:
for (int i = 0; i < array.length; i++) {
//String append with orderid and array[i];
}
You can achieve this as below way,
public static void main (String[] args) throws java.lang.Exception
{
String strData[] = {"1","2","3"};
String result = Arrays.toString(strData); // OutPut [1,2,3]
result = result.substring(1, result.length() - 1); // OutPut 1,2,3
result = result.replaceAll(",", ", OrderId=");
System.out.println("Order with OrderId=" + result);
//OutPut Order with OrderId=1, OrderId=2
}
what I want to do:
I want to extract every string from a string array to a different string variable.
Outputting this to the console is no problem of course, just iterate over the array.
But when it comes to assigning each value to a different variable, I dont get any further right now. All I found online were suggestions on how to concatenate each index of the array. That is not what I want. I had a similar solution for ints some time ago, but I cannot come up with it right now.
int answerPackagerCounter = 0;
String answerPackager = "answer" + answerPackagerCounter;
String answer0 = "";
String answer1 = "";
String answer2 = "";
String answer3 = "";
boolean correct0 = false;
boolean correct1 = false;
boolean correct2 = false;
boolean correct3 = false;
for(int k = 0; k < answers.size(); k++ ){
answerPackager = answers.get(k);
}
Of course this does not work, since each time answerPackager is overwritten. I'm quite sure not much is missing here, but I can't see it right now.
Any input is appreciated, thanks in advance!
What I've read is that a Map is probably the best way to go. Where the key can be treated as your separate variable and the value of each key is the value.
You probably would want to create an string array of answer & correct variables that will hole answer0, answer1, etc... & correct0, correct1, etc... That way you can avoid hardcoding
public static void main(String[] args) throws Exception {
String[] answers = new String[] { "Blah1", "Blah2", "Blah3", "Blah4" };
String[] correct = new String[] { "false", "true", "false", "false" };
Map<String, String> answersCorrect = new HashMap();
for (int i = 0; i < answers.length; i++) {
answersCorrect.put("answer" + i, answers[i]);
}
for (int i = 0; i < correct.length; i++) {
answersCorrect.put("correct" + i, correct[i]);
}
// Keys are not stored in order of setting
for (String key : answersCorrect.keySet()) {
System.out.println("Key: " + key + " Value: " + answersCorrect.get(key));
}
System.out.println("");
// Direct usage
System.out.println(answersCorrect.get("answer0") + " " + answersCorrect.get("correct0"));
}
Results:
How about making two arrays, String[] answer = new String[4]; Boolean[] correct= new Boolean[4];
Better, create a class like this:
public Class Answers {
private String[] answer = new String[4];
private Boolean[] correct= new Boolean[4];
... Usuals getters and setters...
}
I have an array of elements and I want to use the elements in the array as variables.
I want to do this because I have an equation, the equation requires multiple variable inputs, and I want to initialize an array, iterate through it, and request input for each variable (or each element of the array).
So I have an array like this:
String variableArray[] = {"a", "b", "c"}
And now I'm iterating through this array and getting the input from the user:
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
int variableArray[i] = keysIn.nextInt();
}
The problem is this line doesn't compile:
int variableArray[i] = keysIn.nextInt();
In essence, I want to use the elements of the array variableArray[] (i.e. a, b, and c) as variables so I don't have to do the same process for each variable. I can't imagine how it's done when there are many variables to input (I wouldn't want to type that all out).
tl;dr I want to streamline the process of inputting values for multiple variables.
You initialized your array as:
String variableArray[] = {"a", "b", "c"}
i.e. an array of Strings.
If you want to refer later to the i-th element, you just write:
variableArray[i]
without any int before - you can't initialize single entries in a array.
Java doesn't work like that. "a" is a string literal, and you can't use it as if it were a variable. There's no magical way to go from having an array element whose value is "a" to having an int variable called a.
There are, however, some things you can do that are probably equivalent to what you want.
String variableArray[] = {"a", "b", "c"}
int valueArray[] = new int[variableArray.length];
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
valueArray[i] = keysIn.nextInt();
}
To get the value of "a", do valueArray[0].
Here's another more sophisticated suggestion:
String variableArray[] = {"a", "b", "c"}
HashMap<String, Integer> variableValues = new HashMap<String, Integer>();
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
variableValues.put(variableArray[i], keysIn.nextInt());
}
To get the value of "a", do variableValues.get("a").
Two things;
Firstly you've declared your array as and array of Strings so variableArray[i] = keysIn.nextInt() won't work any way, int can't be stored in a String array.
Secondly, int variableArray[i] = keysIn.nextInt(); is incorrect, because variableArray has already been declared (as a String array and variableArray[i] is a String element of that array)
The line should read variableArray[i] = keysIn.next();, but this will store the text the user has entered, not a numerical value.
What it could look like is...
String labelArray[] = {"a", "b", "c"}
int variableArray[] = new int[3];
// You could declare this as
// int variableArray[] = {0, 0, 0};
// if you wanted the array to be initialized with some values first.
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", labelArray[i]);
variableArray[i] = keysIn.nextInt();
}
UPDATED
int a = variableArray[0];
int b = variableArray[1];
int c = variableArray[2];
Please use with caution, but after reading your comments to the other answers, you might get a little closer to the way you want it using reflection:
import java.lang.reflect.Field;
import java.util.Scanner;
public class VariableInput {
public static class Input {
public int a;
public int b;
public int c;
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
Scanner keysIn = new Scanner(System.in);
Field[] fields = Input.class.getDeclaredFields();
Input in = new Input();
for (int i = 0; i < 3; i++) {
System.out.printf("Enter value for %s: ", fields[i].getName());
fields[i].set(in, keysIn.nextInt());
}
int d = in.a + in.b + in.c;
System.out.println("d=" + d);
}
}
What you are actually looking for is a Map. It's a collection of mappings from one value to another value. In your case, you can use it to assign an integer value (the value of a variable) to a string that represents the name of a variable.
Therefore you would create an instance of a Map<String, Integer> - read "a map from String to Integer".
See this tutorial for details on the subject.
Now what would your code look like with it:
String[] variableNames = { "a", "b", "c" };
// create the map object
Map<String, Integer> variableValues = new LinkedHashMap<String, Integer>();
// read variable values and put the mappings into the map
for (int i = 0; i < variableNames.length; i++) {
System.out.printf("Enter value for %s: ", variableNames[i]);
variableValues.put(variableNames[i], keysIn.nextInt());
}
// print value of each variable
for (int i = 0; i < variableNames.length; i++) {
String varName = variableNames[i];
System.out.println(varName + " = " + variableValues.get(varName));
}
Output:
Enter value for a: 5
Enter value for b: 4
Enter value for c: 8
a = 5
b = 4
c = 8