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
Related
I'm trying to get the unique words within a string then storing it within an array along with the amount of times it occurs.
My approach towards this was to assign a unique integer to each unique string within an if-else statement, then taking the unique counts of those integers, and pulling any one word from the string that's assigned a unique value, and finally taking the number of times the unique integer occurs.
However, whenever I get to assigning a unique value to the String I get null:
import java.util.Arrays;
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
int[] numbers = null;
if(text.equals("Win")) {
numbers= new int[1];
}else if(text.equals("Draw")){
numbers = new int [2];
}else if(text.equals("Loss")) {
numbers = new int [3];
}
System.out.println(Arrays.toString(numbers));
}
}
Expected output:
{1, 1, 1, 1, 2, 2, 3, 3}
EDIT:
How could this be implemented in a general sense? Such that, I did not know the String had "Win, Loss, Draw" in the string, but I'd want to assign a unique integer to any given unique word?
you have many problems with your code.
first, you have to get each word of the string individual, so you need to split it into array.
second, you need to create one array, and in it to put the integers. (what you did is to create new array for each number)
I tried to fix the problems. hope you understand my code.
(I only fixed your code, and not make it generial)
String[] arr = text.split(" ");
int[] numbers = new int[arr.length];
for (int i=0;i<arr.length;i++){
if(arr[i].equals("Win")) {
numbers[i] = 1;
}else if(arr[i].equals("Draw")){
numbers[i] = 2;
}else if(arr[i].equals("Loss")) {
numbers[i] = 3;
}
}
When creating an object of an array, the number in the brackets new int[1] you declare the length of the array. I'd recommend using a HashMap for that matter. An example of code would be:
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (String word : text.split(" ")) { // loops through each word of the string
// text.split(" ") returns an array, with all the parts of the string between your regexes
// if current word is not already in the map, add it to the map.
if (!counts.containsKey(word)) counts.put(word, 0);
counts.put(word, counts.get(word) + 1); // adds one to the count of the current word
}
// lambda expression
counts.forEach((string, integer) -> System.out.printf("amount of \"%s\": %d\n", string, integer));
}
}
Output:
amount of "Draw": 2
amount of "Loss": 2
amount of "Win": 4
Edit (response to tQuadrat):
I edited this post to keep everything clean and readable.
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (String word : text.split(" ")) { // loops through each word of the string
// text.split(" ") returns an array, with all the parts of the string between your regexes
// if current word is not already in the map, add it to the map.
if (!counts.containsKey(word))
counts.put(word, counts.size() + 1); // index of the word (+ 1 because your expected output was 1-indexed)
}
for (String word : text.split(" ")) {
System.out.print(counts.get(word) + " ");
}
}
}
Output:
1 1 1 1 2 2 3 3
Let's try this approach:
Get the number of words in the String: var words = text.split( " " ); This assumes that words are separated by blanks only.
Create registry for the words: Map<String,Integer> registry = new HashMap<>();
Create the result array: var result = new int [words.length];
Now loop over the words and check if you have seen the word already:
for( var i = 0; i < words.length; ++i )
{
result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
}
Finally, print the result: System.out.println( Arrays.toString( result ) ); – although this would use […] instead of {…}.
registry.computeIfAbsent( words [i], $ -> registry.size() + 1 ); adds a new entry to the registry for each unseen word and assigns the size of the registry plus one as the unique number for that word. For already known words, it returns the previously assigned number.
This works for any set of words in text.
So the complete thing may look like this:
public final class StringLearning
{
public static final void main( final String... args )
{
final var text = "Win Win Win Win Draw Draw Loss Loss"; // … or any other text
final var words = text.split( " " );
final Map<String,Integer> registry = new HashMap<>();
final var result = new int [words.length];
for( var i = 0; i < words.length; ++i )
{
result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
}
System.out.println( Arrays.toString( result ) );
}
}
Maintain the unique value for each word of string in map and then fetch the unique value while assigning your array.
String text = "Win Win Loss Draw Hello";
String[] split = text.split(" ");
// To maintain unique value for each word of input string
Map<String, Integer> = new HashMap<>();
int counter = 0;
for(String ele:split)
if(!map.containsKey(ele))
map.put(ele, ++counter)
// Getting unique value for each word and assigining in array
int[] array=new int[split.length];
for(int i=0; i<split.length;i++)
array[i] = map.get(split[i]);
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]);
}
I'm trying to populate an array [C], then display it using a for loop.. I'm new to arrays and this is confusing the hell out of me, any advice is appreciated!
Below is my code:
public static void main(String[] args) {
int A[] = new int[5];
int B[] = new int[5];
String C[] = new String[5];
int D[] = new int[5];
C[] = {"John", "Cook", "Fred"};
for(String name: C)
System.out.println(C);
}}
You can define and populate an array in two ways. Using literals:
String c[] = {"John", "Cook", "Fred"};
for(String name : c) { // don't forget this { brace here!
System.out.println(name); // you want to print name, not c!
}
Or by setting each index element:
int d[] = new int[2];
d[0] = 2;
d[1] = 3;
for(int num: d) {
System.out.println(num);
}
(You can only use the literal when you first define the statement, so
String c[];
c = {"John", "Cook", "Fred"};
Will cause an "illegal start of expression" error.)
You want to print name instead of C.
C is the name of the array, while name is the name of the String variable. Therefore you must print name instead of C
System.out.println(name);
for(int i=0;i<=2;i++){
System.out.println(C[i]);
}
here 2 is the last index of the array C
You cannot simply print an array you have to provide an index to your item
where C[0] is john and C[1] is Cook and so on
and if you want to use a for each loop then this is how it goes
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
Try specifying at what index you want to add the element.
Example:
C[0] = "hej";
Also, print the element in the array, not the actual array. (System.out.println(name);)
I have two arrays of Type String:
String [] a;
String [] b;
and then a map
Map<String, String> mapNumeric = new HashMap<String, String>();
I want a to be the keys and b the value. So it will look like this:
elementOfA = elementOfB
otherElementOfA = otherElementOfB
And so on...
mapNonNumeric.put( a, b); does not work I tried to pass element by element by doing:
for( String key : a) {
mapNumeric.put( key, new String() );}
for( String value: b) {
mapNumeric.put(new String(), value );}
That is not good either because the new String() will erase the previous value. Also if you do nested for loops it assigns all the values of the array b as values of the first element of array that will create the keys.
Please help if someone knows how to assign one array for the keys and another array for the values of the same map, or if you know other structure that will do the trick. Thanks.
PS I am working in Java
Update
Fix the String[] I am learning how to use maps so it was a mistake. Thanks to your advise is now working
You declared the map to use arrays of strings to be used.
If you want to put(x,y) where x and y are String , then you have to declare it Map<String,String>.
For your case, x would be one element of a , y an element of b.
You'll have to iterate over a and b to insert all of them into the Map as you can see in various answers by now.
Try this:
String [] a = getA();
String [] b = getB();
Map<String, String> mapNumeric = new HashMap<>();
for (int i=0; i < Math.min(a.length, b.length); i++) {
mapNumeric.put(a[i], b[i]);
}
The way you defined it you have one array as a key and the other one as the value for that key. You may want it like this:
String[] keys = getKeys(); // magic
String[] values = getValues(); // magic
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i];
}
(assuming keys and values have the same length)
String [] a = whatever;
String [] b = whatever;
int minSize = Math.min(a.length, b.length);
Map<String, String> mapNumeric = new HashMap<String, String>(minSize);
for (int i = 0; i < minSize; i++) {
mapNumeric.put(a[i], b[i]);
}
Context: I have converted an array into a string, then into bytes so that it can be stored as a blob in a database. I then want to retrieve the array. I retrieve the blob and retrieve the string from the bytes. I then want to retrieve the array from the string.
Now I had been looking at various options to convert my string back into an array. I had looked at using string.split() with certain regex to get my array back, however, this gets a bit complicated with it being multidimensional. However is there a simple way to convert a string back to array where the string still contains its original "array syntax"?
e.g.
Array array = {1, 2, 3}
String string = array.toString()
[insert string back to array]
Cheers!
p.s. can an array be stored in a database (google app engine) without the need for this inefficient convoluted method?
You can store the List as a EmbeddedProperty.
For example, here you have the general utility class I use for those kind of needs...
import java.util.ArrayList;
import java.util.List;
import com.google.appengine.api.datastore.EmbeddedEntity;
/**
* Utility class for storing Lists of simple objects
* #author toni.navarro
*
*
*
*/
#SuppressWarnings("unchecked")
public class ListTransformer<T> {
public List<T> toList(List<EmbeddedEntity> embeddedList) {
List<T> list = new ArrayList<T>();
if (embeddedList!=null) {
for (EmbeddedEntity embeddedEntity: embeddedList) {
list.add((T) embeddedEntity.getProperty("value"));
}
}
return list;
}
public List<EmbeddedEntity> toEmbeddedList(List<T> list) {
List<EmbeddedEntity> embeddedList = new ArrayList<EmbeddedEntity>();
if (list!=null) {
for (T item: list) {
EmbeddedEntity embeddedItem = new EmbeddedEntity();
embeddedItem.setUnindexedProperty("value", item);
embeddedList.add(embeddedItem);
}
}
return embeddedList;
}
}
... and then use it with something like:
embeddedEntity.setUnindexedProperty("possibleQuestions", new ListTransformer<Long>().toEmbeddedList(turn.getPossibleQuestions()));
... and:
turn.setPossibleQuestions(new ListTransformer<Long>().toList((List<EmbeddedEntity>)embeddedEntity.getProperty("possibleQuestions")));
Why would you store it as blob? Convert the array to a string: "1,2,3". Then, when loading, do something like: loadedString.split(",") and iterate over the array (the result of the split() method is String[]) and add it to the Array data structure that you are using.
Use the split method which parses a string accorign tot a given delimiter and returns an array out of it.
Take a look at this exmaple:
//split string example
String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = asseltClasses.split(":");
System.out.println("splits.size: " + splits.length);
for(String asset: assetClasses){
System.out.println(asset);
}
OutPut
splits.size: 5
Gold
Stocks
Fixed Income
Commodity
Interest Rates
Convert string into two dimensional string array in Java gives the answer.
In particular:
If you know how many rows and columns there will be, you can pre-allocate a String[][] and use a Scanner as follows:
Scanner sc = new Scanner(data).useDelimiter("[,|]");
final int M = 3;
final int N = 2;
String[][] matrix = new String[M][N];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
matrix[r][c] = sc.next();
}
}
System.out.println(Arrays.deepToString(matrix));
// prints "[[1, apple], [2, ball], [3, cat]]"
public static void main(String[] args) {
String s = "my name is abc";
StringTokenizer strTokenizer = new StringTokenizer(s);
List<String> arrayList = new ArrayList<String>();
while (strTokenizer.hasMoreTokens()) {
arrayList.add(strTokenizer.nextToken());
}
List<List<String>> lst = new ArrayList<List<String>>();
lst.add(arrayList);
for (int i = 0; i < lst.size(); i++) {
for (int j = 0; j < 1; j++) {
System.out.println("Element " + lst.get(j));
}
}
}