1

I'm very new to Java, and learning on my own. Here's a problem I'm struggling with.

I'm wonder if we can set a string variable to one thing then use if else statements to change it to something else?

What I am thinking with codes:

String superscript = "th";
while (i<=10){ 
      if (i==1){
      String superscript = "st";
      }
      System.out.println("the " + i + superscript +" element is: " + X);
      i++;
}

Essentially, what I want is that if i==1, it displays 1st, and i==2, it displays 2nd, and so on and so forth with only one string variable "superscript."

And, how do I make two if conditions to change superscript to "nd" when i==2? How do I use if statement here?

1
  • Thanks for all the wonderful suggestions :) Commented May 10, 2015 at 2:09

5 Answers 5

2

You can reassign to an existing variable, but to do that, you need to omit the type declaration; when you specify the type, you are declaring a new variable (albeit with the same name). That is:

while (i <= 10){
   String superscript = "th"; 
   if (i == 1){
     superscript = "st";
   }
   System.out.println("the " + i + superscript +" element is: " + X);
   i++;
 }

... reassigns to the existing superscript variable. That being said, we can improve upon this a lot further by using a for-loop and also creating a subroutine for this formatting:

for (int i = 0; i < 10; i++) {
     String element = arr[i];
     System.out.println("the " + asOrdinal(i+1) + " element is: " + element);
}

... with a helper function "asOrdinal" defined like this:

private static String asOrdinal(int index) {
   String suffix = "th";
   int onesDigit = index % 10;
   switch (onesDigit) {
     case 1:
       suffix = "st";
       break;
     case 2:
       suffix = "nd";
       break;
     case 3:
       suffix = "rd";
       break;
     default:
       suffix = "th";
       break;
   }
   return Integer.toString(index) + suffix;
}

Note that my default case above is somewhat redundant (the string was already initialized with this default), but is there to illustrate how "default" works in a switch statement. You could also use a "return" in each of the different cases instead of assigning to the same local variable. I generally prefer to use "return", since assigning to the same variable repeatedly is often a code smell (or, rather, it isn't "functional" style, which tends to be my preference). In short, as you can see from the many answers here, there are multiple different ways to do the same thing.

The key take away you should get is that:

// Outer scope
TypeOfVariable identifier [= initialization_expression1];

// Inner scope
{
   TypeOfVariable identifier [= initialization_expression2];

   // ... usage ...
}

... in the above, the inner usages of "identifier" are referencing the variable that was declared in the inner scope. This variable is in a different memory location from the one declared in the outer scope (though, if it is an object pointer, both can point to the same value if they have been assigned/initialized with the address of the same object).

By contrast:

// Outer scope
TypeOfVariable identifier [= initialization_expression1];

// Inner scope
{
   identifier = expression2;

   // ... usage ...
}

... in the above, the "=" statement is not initialization but assignment, and both variables in the inner and outer scope are the same (with the statement in the inner scope replacing/assigning its value).

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

Comments

1
String superscript = "th";
int i = 0;
while (i<=10){ 
    if (i==1){
        superscript = "st";
    }else if (i==2){
        superscript = "nd";
    }else if (i==3){
        superscript = "th";
    }
    System.out.println("the " + i + superscript +" element is: " + X);
    i++;
}

Comments

1

Your problem is that you create a new local variable called "superscript" inside the if statement but in the println you use the one declared outside the while statement. You shouldn't write String before "superscript" in the if statement.

Edit: I was late :)

Comments

1

This is a classic situation for the switch case construct:

int i=1;
String superscript;
while (i<=10) {
  switch (i) {
  case 1:
    superscript = "st";
    break;
  case 2:
    superscript = "nd";
    break;
  case 3:
    superscript = "rd";
    break;
  default:
    superscript = "th";
  }
  System.out.println("the " + i + superscript +" element is: " + X);
}

Comments

0

Just reassign it instead of creating a new variable. Also, if you move the initial 'th'-definition inside the while loop, you will avoid another if statement.

Keep in mind that the 'teen'-numbers are special, but apart from that the ordinal suffix depends on what the last digit in the number is.

public class Ordinal {

    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            String superscript = "th";
            if (i == 1) {
                superscript = "st";
            }
            if (i == 2) {
                superscript = "nd";
            }
            if (i == 3) {
                superscript = "rd";
            }
            System.out.println("the " + i + superscript + " element is: ");
            i++;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.