user1639780
user1639780

Reputation:

Trying to read through a character array in java

I am a newcomer trying to learn java. I am doing a project for my class in which we are creating a hexadecimal-decimal converter. I already have the conversion finished, but when I print out the hexadecimal result, the letters (because hexadecimal contains A-F) print out in lowercase. I tried the following code to read through the character array and capitalize any lowercase characters:

int i = Integer.parseInt(input);
String hex = Integer.toHexString(i);
char[] hexchar = hex.toCharArray();
for(int j=0; j<=hexchar.length; j++){
   if(hexchar[j].equals("a")){
     hexchar[j]=hexchar[j].toUpperCase();
} 
}

I was going to set up this code for the letters a-f, but the error I keep getting is that a Char array can't be deferred. Does anyone know if there is a way to read through the char array or can submit a possible workaround?

Upvotes: 1

Views: 2096

Answers (4)

user1639637
user1639637

Reputation: 29

Here you go:

import java.util.Scanner;

public class classy
{
    public static void main(String args[])
    {
        Scanner input = new Scanner( System.in );

        int i;

        System.out.println("Please enter an integer");
        i=input.nextInt();

        System.out.printf( "Your Integer  is  %d\n", i );


        String hex=Integer.toHexString(i).toUpperCase();
          System.out.println("Your Hexadecimal Number is  "+hex);
    }
}

Upvotes: 0

codeDisaster
codeDisaster

Reputation: 59

Shouldn't this work perfectly fine.

int i = Integer.parseInt(input);
    String hex = Integer.toHexString(i);
    System.out.println(hex);
    System.out.println(hex.toUpperCase());

It will change all the chars from a-f to A-F and keep the numbers intact.

Upvotes: 0

obataku
obataku

Reputation: 29656

char is a primitive. Maybe you meant Character.toUpperCase?

final int i = Integer.parseInt(input);
String hex = Integer.toHexString(i);
final char[] cs = hex.toCharArray();
for (int j = cs.length; j > 0; --j) {
  final char ch = cs[j];
  if (Character.isLetter(ch)) {
    cs[j] = Character.toUpperCase(ch);
  }
}
hex = new String(cs);

I don't see the point, though; you should really just use String.toUpperCase, so...

final String hex = Integer.toHexString(i).toUpperCase();

Upvotes: 0

assylias
assylias

Reputation: 328825

You can't apply toUpperCase to a char, which is a primitive: it is a method of the String class. The following code should do what you want:

int i = Integer.parseInt(input);
String hex = Integer.toHexString(i).toUpperCase();

Upvotes: 3

Related Questions