Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.