These are the steps the program must follow:
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.
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
}
Use Integer.valueOf(String.valueOf(digit), 16)
to do the conversion. If you change your digit
and make it String
, you don't need to do the String.valueOf(...)
Result:
In: 1234
Out(hex): 4660
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.