-1

I have this chunk of code that I've been having problems with:

    int n = 5;
    String[] variables = new String[31];
  //user input defining the strings in the array
for(int i = 1; i < n+1; i++)
{
    System.out.print("Define variable " + i + ": ");
    variables[i] = System.console().readLine();
    System.out.println("Variable " + i + " has been set to " + variables[i]);
}
int vfirstDigit;
  //some irrelevant code excluded
for(int firstDigit = 1; firstDigit < n+1; firstDigit++)
{
    switch(firstDigit)
    {
        case 1:             
        vfirstDigit = variables[1];
        break;              
    }
}

When I call variables[1] in the switch statement, the compiler flags it as an error, saying the String array cannot be converted to an integer. Why does calling a specific string in the array convert it to an integer, when the user input must be characters? Pretty sure I'm doing something wrong here.

1
  • if your string contains JUST number, you have t parse it. Can you post up your switch statement too? Commented Jun 22, 2014 at 16:20

2 Answers 2

0

Array is an object. You need to convert it in number by using method parseInt of Integer.

Sign up to request clarification or add additional context in comments.

Comments

0

use,

vfirstDigit = Integer.parseInt(variables[1]); // vfirstDigit is an int and variables[1] returns a String. you have to convert (parse) the String to an int.

parseInt() is a static method in Integer class. It has many overloaded forms (i.e, many forms which take different arguments).It returns the integer representation of the value passed.

4 Comments

how do you the content of variable contains numbers for sure?
@KickButtowski - Then he will endup with a NumberFormatException. Its something that must be taken care by the OP.
Awesome, it looks like it works. Can you explain what that does please? Trying to learn :D
Thanks for the help guys, that cleared up a bunch of problems I've been having!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.