Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Arrays Posted by helen1974 on 19 Mar 2012 at 4:20 AM
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;
}
}

}
}

Report
Re: Arrays Posted by Wirus on 28 Mar 2012 at 3:35 AM
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.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.