Does Java have global variables?

How to make variables out of an array - java?

  • I'm writing a translator that translates code from a programming language my professor made up to java code. I hit a snag at one point, and made a class to test my problem out. My code looks like this, and my intention is to create an int variable out of each char stored in the char array: public static void main(String[] args) { char[] array = {'a','b'}; for(int i = 0; i < array.length; i++) { int array[i] = args.length; } } my intention is to initialize variables that look like (int a = args.length) (int b = args.length) etc Any ideas?

  • Answer:

    I am not sure you could create a new variable while looping through an array? Could you do it manually 1 by 1? like array[0] = int num; array[1] = int num2; etc. But it may not like changing a char to an int? Why you would want to do that is kind of confusing me.

Ryan at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Actually you want each element of args[] in an individual int variable so you can do it this way: public static void main(String[] args) { int array[] = new int[args.length]; //declare an int array of size equal to args[] for(int i = 0; i < args.length; i++) { array[i] = Integer.parseInt(args[i]); // each element of args[] will be stored in corresponding location of array } } Now all the string number elements of args[] are converted to numerals in array[]. You can now use it in the same way as you would have used individual variables. for(int i=0;i<array.length;i++) { // array[i] can be used here for whatever was your purpose }

Amita

Let's say your professor passed in args[ 5000000 ] Your for-loop would then fail to initialize one int[] array named 'array' two times. Should be: int [] array = new int[ args.length ]; at least you would have ONE array with 5 million Zeros until the code is done with the for loop. The scope of int[], named 'array' is garbage-collected after the closing brace of the for-loop.

deonejuan

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.