I am a beginner in Java and am working on a Mastermind project for a course.
I have a problem. I want to retrieve the value of leftDigit
and put it into array guess[4]
. But I don't know how to retrieve it outside the loop.
Let's say when I input the number 1234 and I want it to become int[] guess = { 1, 2, 3, 4};
`
public static void inputNumber(){
Scanner input = new Scanner(System.in);
currentRow++;
System.out.printf ("Enter 4 numbers for attempt #%d: ", currentRow);
int count = 10000, leftDigit;
double tempNum;
int number = input.nextInt();
//finding the left digit
do{
tempNum = (double) number / count ;
leftDigit = (int) (tempNum * 10) ;
count /=10;
number = number - ( count * leftDigit);
} while (count != 1 );
}
int [] guess = new int[4];
int i = 0;
//finding the left digit
do{
tempNum = (double) number / count ;
leftDigit = (int) (tempNum * 10) ;
guess[i++] = leftDigit;
count /=10;
number = number - ( count * leftDigit);
} while (count != 1 );
//Use guess as you want it contains the 4 digits you need
The solution which was posted works, but there are a few things that are unnecessary tho. Here's the code and I'll explain below:
int count = 1000; // notice I start at 1000, not 10_000
int[] guess = new int[4];
int i = 0;
do {
guess[i++] = number / count; // (1)
number %= count; // (2)
count /= 10;
} while (count != 1)
(1): because both number and count are typed int , the result will not be a floating point number and it won't be rounding up. it'll just truncate the floating part. For example: 8 / 3 == 2; 543 / 1000 == 0.
(2): This line will get the remainder of the division. For example: 16 % 5 = 1; 1043 % 1000 = 43. (Another way to write this line would be number = number % count
).
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.