0

These are the steps the program must follow:

  1. Request user input for 4 digit pin. [done]
  2. Convert 4 digit pin to hexadecimal. [?]
  3. Generate two random numbers greater than 1000 and convert to hexadecimal.[?]
  4. Sandwich the converted pin between the two random converted numbers. [can be done]

So far the code I have is:

public static void main(String[] args) 
{
    int digit = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    digit = scan.nextInt(); // scanning for user input

    String Hexpin =Integer.toHexString(digit);
    System.out.println(Hexpin); 
}

I currently need help converting the pin to hexadecimal and generating two random numbers greater than 1000 and converting them to hexadecimal also. I can then however do the sandwich easily. I tried searching for an answer before this and cant find anything other than:

C# convert integer to hex and back again

This article however converts the int to a hex string not a decimal.

halfer
  • 18,701
  • 13
  • 79
  • 158
Guru
  • 56
  • 2
  • 13
  • `// unusual result?` - what's unusual about it? – Eran Nov 14 '17 at 11:24
  • Edit: the result is not unusual just tested again, please ignore previous comment I made. – Guru Nov 14 '17 at 11:25
  • if all you're doing is printing the number in hex, the easiest approach is `System.out.printf("%x", digit);`. To "sandwich" it: `System.out.println("%x%x%x", before, digit, after);`. – Andy Turner Nov 14 '17 at 11:39

3 Answers3

1

Give this a try I think this is what you are asking for. Just needed a small fix. Hope that helps!

    public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    int digit = scan.nextInt(); // scanning for user input as INT
    String hexDigit = Integer.toHexString(digit); //convert PIN to hex

    int one = ((int)(Math.random()+1000)*10000); //two randoms bw 1000 and 10000
    int two = ((int)(Math.random()+1000)*10000);

    String oneStr = Integer.toHexString(one); //convert to hex
    String twoStr = Integer.toHexString(two); //convert to hex

    System.out.println(oneStr + hexDigit + twoStr); //print concated
}
G2M
  • 68
  • 1
  • 6
0

Use Integer.valueOf(String.valueOf(digit), 16) to do the conversion. If you change your digitand make it String, you don't need to do the String.valueOf(...)

Result:

In: 1234 
Out(hex): 4660
canillas
  • 408
  • 3
  • 11
0

To convert to Hexadecimal use:

String Hexpin = Integer.toHexString(digit);

To convert back to integer use:

int numberFromHex = Integer.parseInt(Hexpin, 16);

Be clear on what you call unusual result in your code comment.

Tharun
  • 301
  • 2
  • 13