Arrays - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Arrays

helen1974helen1974 Posts: 4Member
Hi all,

I am new to java and I recently began working on Array's, which may seem to be difficult but surprisingly I have taken to them.

The following code is what my lecturer wants me to produce, but I think there must be a shorter way to achieve the same thing, take a look and let me know please.


import java.util.Scanner;
public class dec2hex
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter the number");

int number=input.nextInt();
String output="1";
int n=0;

while (number>=16*n)
{
n++;
}

n=n-1;
int newnum=number-16*n;

if(newnum>=0&&newnum<=9)
{
System.out.print(n+" "+newnum);
}
else if(newnum==number)
{
while(Math.pow(16,n)<=newnum)
{
n++;
}
n=n-1;
for( int i=0;i<n;i++)
output+="0";
System.out.print(output);
}

else if(newnum>9)
{
switch(newnum)
{
case 10: System.out.print(n+"A"); break;
case 11: System.out.print(n+"B"); break;
case 12: System.out.print(n+"C"); break;
case 13: System.out.print(n+"D"); break;
case 14: System.out.print(n+"E"); break;
case 15: System.out.print(n+"F"); break;
case 16: System.out.print((n+1)+"0"); break;
}
}

}
}

Comments

  • WirusWirus Posts: 10Member
    Hi Helen,

    I didn't try to focus on your code, just did conversion as in class name (dec 2 hex)

    import java.io.Console;
    import java.util.Scanner;

    public class dec2hex {
    public static void main(String[] args) {
    Console console = System.console();
    int number = 0;
    if (console == null) {
    Scanner input=new Scanner(System.in);
    System.out.print("Enter the number: ");
    number = input.nextInt();
    } else{
    String in = console.readLine("Enter the number: ");
    number = Integer.parseInt(in.trim() );
    }

    System.out.println( Integer.toHexString( number ) );
    }
    }

    Of course, you may remove console, or Scanner, if you wish.
Sign In or Register to comment.