简体   繁体   中英

Three digit lottery program in java

I just started an intro to java programming class so I do not know much. I am having trouble obtaining the middle digit of the lottery variable. I used int lotteryDigit1 = lottery / 100; and int lotteryDigit2 = lottery % 100; to get the first and last number but I am having trouble getting the middle digit.

import java.util.Scanner;
public class Lottery {`enter code here`
    public static void main(String[] args) {

        //generate random lottery numbers 
        int lottery = (int)(Math.random() * 100);



        //ask user to enter a 3 digit guess
        Scanner numbers = new Scanner(System.in);
        System.out.println("Please enter your lottery pick. Three Digits Only");
        int guess = numbers.nextInt();

        //digits for lottery
        int lotteryDigit1 = lottery / 100;

        int lotteryDigit2 = lottery % 100;


        //digits for guess
        int guessdigit1 = guess / 100; 
        int guessdigit2 = guess % 100; 

try this code

int lottery = 123;
System.out.println(lottery);
System.out.println(lottery % 10);
System.out.println(lottery % 100 / 10);
System.out.println(lottery / 100);

output

123
3
2
1

You can write small util function to return digit at given position:

public static int digitAt(int input, int position){     
    int i =(int) (input % (Math.pow(10, position)));
    int result = (int) (i / Math.pow(10, position - 1));
    return result;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM