So I have to create three random numbers using the Math.random(); method then use a for loop to output each number by itself and then using a concatenate to make them into a string. It’s for my assignment. I’ve done everything else. I could do it a different way but it requires a for loop. I can’t use the Random class. I have not learned it in my course, therefore it can’t be applied.
public class Lottery
{
public static void main(String[] args)
{
//declare and initialized variables and objects
Scanner input = new Scanner(System.in);
//Identify the repeated steps and use a for loop structure
for(int i=0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
String lotteryNumberString = Integer.toString(lotteryNumberDigit);
}
String firstNumber = lotteryNumberString.substring(0,0);
String secondNumber = lotteryNumberString.substring(1,1);
String thirdNumber = lotteryNumberString.substring(2,2);
String firstTwoWinner = firstNumber + secondNumber;
String lastTwoWinner = secondNumber + thirdNumber;
String allNumbersWinner = firstNumber + secondNumber + thirdNumber;
System.out.println("Please enter your three numbers (e.g. 123): ");
String userInput = input.next();
if(userInput.substring(0,2).equals(firstTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the front pair matched.");
}
else if (userInput.substring(1,3).equals(lastTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the end pair matched.");
}
else if (userInput.equals(allNumbersWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, both pairs matched.");
}
else
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Sorry, no matches. You only had one chance out of 100 to win anyway.");
}
}
}
I had to take out the arrays because my teacher said it was not expectable until the next chapter.
You can simply write below to print the 3 digit number.
Note: By using
printmethod, you will print the three digits next to each other.Alternatively you can do below:
If you want to get the number from string, you can simply do:
EDIT:
If you don’t want to use
Randomclass, do the below(updating first example only. Same can be applied into second as well):Edit: for you next problem, define an
int[]in the beginning and store the values in the array for later use of comparison. Updated code snippet as below:After the above loop,
generatedNumberswill contain all three digits as separate entry in the array. Your comparison code can be as below:EDIT:
Please do the comparison as below: