1

When I attempt to convert a number from hexadecimal to decimal i.e., I enter 2 as the first input, the output comes,

'Enter a hexadecimal number

converted to decimal is 0'

It never waits for me to enter the string. I have commented where it doesn't accept the string. Can someone figure out what's wrong?

Thanks!

 public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    DecimalToHexadecimal ob=new DecimalToHexadecimal();
    int op;
    do 
    {
        System.out.println("To convert decimal to hexadecimal enter 1 and to convert hexadecimal to decimal enter 2");
        op=sc.nextInt();
        if (op!=1 && op!=2)
        {
            System.out.println("Error!");
        }
    }while (op!=1 && op!=2);
    if (op==1)
    {
         int n;
         do
         {
             System.out.println("Enter a number");
             n=sc.nextInt();
             if (n<0)
             {
                 System.out.println("Error!");
             }
         }while (n<0);
         String hexa=ob.decimaltohexa(n);
         System.out.println(n+" converted to Hexadecimal is "+hexa);
    }
    else 
    {
         int d;
         String hexa="";
         do
         {
             System.out.println("Enter a hexadecimal number");
             hexa=sc.nextLine();  //This is where it doesn't take the input
             d=ob.hexatodeci(hexa);
             if (d!=-1)
             {
                 System.out.println(hexa+" converted to decimal is "+d);
             }
             if (d==-1)
             {
                 System.out.println("Error!");
             }
         }while (d==-1);
    }
}
Shinjinee Maiti
  • 135
  • 1
  • 2
  • 10

1 Answers1

1

You just need to add another sc.nextLine() before you take the input. That will work. Like this:

sc.nextLine();
hexa=sc.nextLine();  

sc.nextInt() does not take the \n at the end of the string when you enter 2, it only takes the numeric part.
This \n is taken by your hexa=sc.nextLine(); as input.
So, an extra sc.nextLine(); will consume that and your code will work.

dryairship
  • 5,702
  • 2
  • 27
  • 52
  • Thanks!! But can you tell me the reason for that? – Shinjinee Maiti Jan 31 '16 at 12:23
  • The reason is in my answer. `sc.nextInt()` does not take the `\n` at the end of the string when you enter 2, it only takes the numeric part. So, the remaining `\n` is taken when you do `hexa=sc.nextLine();` – dryairship Jan 31 '16 at 12:26