armin
armin

Reputation: 19

Loop prints more than once

Hi I am trying to convert from lower to uppercase. I know they are other easier ways to do this, but I want something else. It seems that the program prints out the users input more than once, so I am almost 100% sure it's the loop. But I can't find where the problem is.

String a = input.nextLine();
String c = "";
int b = a.length();

for (int i = 0 ; i < b; i++)
{
    if (a.charAt(i) >= 97 && a.charAt(i) <= 122)
    {
        c = c + a;
        System.out.println(c.toUpperCase());
    }
}

Upvotes: 1

Views: 237

Answers (4)

Lucifer
Lucifer

Reputation: 1

This solution should work:

for (int i = 0 ; i < b; i++)
{
    if (a.charAt(i) > 97 && a.charAt(i) < 122)
    {
        a = a.toUpperCase();
    }
}
System.out.println(a);

Upvotes: 0

FredK
FredK

Reputation: 4084

Why bother going through the loop at all?

String a = input.nextLine();
System.out.println( a.toUpperCase();

will do what you want

If you want to invert the characters:

StringBuffer sb = new StringBuffer(a);
for ( int i=0; i < sb.length(); i++ ) {
   char c = sb.charAt(i);
   if ( c.isLower() ) {
      sb.setCharAt(i,c.toUpper());
   } else if ( c.isUpper() ) {
      sb.setCharAt(i,c.toLower());
   }
}
String result = sb.toString();

Upvotes: 0

QuakeCore
QuakeCore

Reputation: 1926

Actually your code logic wasn't totally right, I mean why would you add the content of a to c? Doesn't make sense, and you excluded the letters a and z in your if.

String a = input.nextLine();
String c = "";
int b = a.length();
for (int i = 0; i < b; i++) {
    if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
        c = c + a.charAt(i);
    }
}
System.out.println(c.toUpperCase());

Upvotes: 1

Mureinik
Mureinik

Reputation: 311348

You're printing c in each iteration of the loop where the if is entered instead of just once, after it ends.

Upvotes: 0

Related Questions