My task is to allow a user to input their lottery numbers and check if
they have won the jackpot.
The user should be given the chance to enter 4 numbers. Each number should be in the range 1-99. If
the user enters a number that is less than 1, or greater than 99, then the programme should prompt
them to enter a number in the correct range. You should use a while loop to ensure that the user inputs
the correct number. What should the exit condition of the while loop be?
I have tried making a while loop as the task asks me to do. this did not work. I am completely and utterly stuck.
String password = "MyNameJeff";
Scanner dave = new Scanner(System.in);
System.out.println("lottery numbers");
int UserInput = dave.nextLine();
while (!password.equals(UserInput)) {
System.out.println random math command <----
UserInput = dave.nextLine();
}
System.out.println("Lottery numbers here?");
This while loop will take the first userInput and check its range between 1 and 99 inclusive.
while(userInput < 1 || userInput > 99){
System.out.println("Please re-enter another lottery number: ");
userInput=dave.nextInt();
}
If it is not in the range 1 to 99, it will request the user to re-enter another lottery number.
the condition is when you want to stop the while loop. for example
you may want to stop when you have 4 numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
List<Integer> choices = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean done = false;
//we set done to false, and the condition is "while !(not) done"
while (!done) {
try {
System.out.println("write lottery numbers:");
String userInput = scanner.nextLine();
Integer result = Integer.parseInt(userInput);
// compareTo is a bit tricky, read the javadoc for information
if (result.compareTo(0) < 0) {
System.out.println("dont add number less then 0");
continue;
}
if (result.compareTo(99) > 0) {
System.out.println("dont add number more then 99");
continue;
}
//adding more result is the only way done will be eventually true
choices.add(result);
//set to done when the size of the list is 4
done = choices.size() == 4;
} catch (NumberFormatException e) {
System.out.println("Only add number");
}
}
System.out.println("Lottery numbers here?");
choices.forEach(System.out::println);
}
}
Check this code
public static void main (String[]args) throws IOException, ParseException {
int [] winNumbers = new int[4];
int [] numbers = new int[4];
int indx=0;
System.out.println("Enter Lottery Numbers");
while (indx<4) {
System.out.println("Enter number: ");
Scanner dave = new Scanner(System.in);
try {
String in = dave.nextLine().trim();
int inNum = Integer.parseInt(in);
if (inNum>0 && inNum<100) {
numbers[indx] = inNum;
indx++;
continue;
}
}
catch (NumberFormatException | NullPointerException nfe) {
}
System.out.println("Please enter a number in the range 1-99");
}
Random rand = new Random();
for (int i=0; i<winNumbers.length; i++){
int r = rand.nextInt(98);//will get a random number between 0-98
r +=1; // for the number to be on the space 1-99
winNumbers[i]=r;
}
System.out.println("User entered: " + Arrays.toString(numbers));
System.out.println("Lottery numbers here: " + Arrays.toString(winNumbers));
}
Two int arrays are used with size 4.
One is filled using Scanner. There are some checks:
trim(): will remove any whitespace that the user might enter
catch: will catch a numberFormatException or null. It will print nothing.
If the code does not enter the if(inNum>0 && inNum<100) then the indx counter will not increment and the code will print the error message: Please enter a number...
The second part of the code generates 4 random numbers and stores them in the second array.
Finally, it prints the two arrays.
Related
I'm writing a number guessing game in java.
Number guessing game is a numeric version of famous hangman, where computer picks a
number between a prespecified range and user has to guess that number.
Requirements:
User must guess a number between 0-1000 and tells the user the range of guessed
number.
User has max 10 guesses.
Every time user makes a guess, total guesses reduce by one.
Computer keeps track of all the numbers user has guessed so far and shows this
information before next guess.
If the guess is correct, game ends in a win. In case of incorrect guess, computer gives a
hint to the user. If the user guess is greater than the picked number, then client tell the
user that ‘your guess is bigger’ and in case of being smaller appropriate message is
shown.
In case of invalid guess (alphabets, symbols and repeated guesses) one warning is given
and on next warning user loses a guess
The following code is running fine but it always shows the same number after guesses number. I think its not adding the new input in the arrraylist rather the first one everytime.
import java.util.*;
import java.lang.*;
public class NumberGuess {
public static void main(String[] args) {
int tries = 10;
ArrayList<Integer> guessed = new ArrayList();
int warnings = 2;
int i = 0;
Random rand = new Random();
int random = rand.nextInt(1000);
private void StartMenu () {
System.out.println("\" Welcome to the Number guessing game!\n I am thinking of a number between 0-1000\n You have 1 warning.\n You have 1 warning.\n ------------ ");
}
public char[] ToCharacterArray (String input){
char arr[] = new char[input.length()];
arr = input.toCharArray();
return arr;
}
public boolean CheckInput ( char arr[]){
if (Character.isDigit(arr[0])) {
return true;
} else {
return false;
}
}
String input;
while (tries > 0 && warnings > 0) {
System.out.println("You have " + tries + " guesses left.");
if (tries == 10) {
System.out.println("guessed number: ");
} else {
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(guessed.get(i));
}
}
System.out.println("Please guess a number:");
Scanner sc = new Scanner(System.in);
input = sc.next();
char InputString[] = ToCharacterArray(input);
if (CheckInput(InputString)) {
int intInput = Integer.parseInt(input);
guessed.add(intInput);
if (intInput > random) {
System.out.println("Your guess is greater");
}
if (intInput < random) {
System.out.println("Your guess is smaller");
}
if (intInput == random) {
System.out.println("Congrats! You win.");
System.out.println("The guessed number is: " + intInput);
tries = -1;
}
}
tries--;
}
}
}
The problem is because you iterate over the guessed numbers, and then print out the item of index i from that list. The number i at that point will always be zero, so it will always print just the first element from that list. Instead, you can just print the a, that is the element itself, after the iteration on guessed. Here is how it will look like:
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(a);
}
I am very new to coding and learning JAVA. I was able to execute the below code but I am not sure how to loop this until the user matches the randomNumber. Could you please help.
My current code:
package com.arwa.basicExcercisePart1;
import java.util.Scanner;
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
You can use a while loop like so:
int number;
while((number = scan.nextInt()) != randomNumber){
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: ");
}
System.out.println("Wow, The entered number matched with the Random Number.");
Put a loop around the code that checks the user's input against the random number.
iota's answer is correct but since Aravind is learning I'd like to suggest another more didactic answer. You can use a flag to signal that the user choose the right answer and then get out of the loop. I did this below:
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
boolean found = false; // flag is false at beginning
while (!found) { // stay in the loop till answer is correct
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
found = true; /// will finish the loop
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
}
package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}
I want to enter several numbers for some operations. But i need to add this numbers without stopping. I mean, for example i wanna that program asks me how many integer i want to enter, after for example i yped 5 and click enter, it should give me opportunity to enter my 5 numbers (For example, 12, 34, 54, 23, 9) in the lines. Then i will use this numbers for something in my program.
i am using Scanner class for entering the number. But i wanna to enter several numbers in once input.
package frlr;
import java.util.Scanner;
public class Frlr {
public static void main(String[] args) {
System.out.println("Please enter your numbers: ");
Scanner in = new Scanner(System.in);
int myNumbers = in.nextInt();
System.out.println(myNumbers);
}
}
I need, when program asks me "Please enter your numbers:" if i enter 5 , it should be the count of the numbers which i will enter in the next steps.
You can use for loop, for loop allows you enter the amount of numbers you entered in your first scanner.
For example:
1) you scan the amount of number you want to enter
2) in for loop you use that number as an endpoint
so your for loop is gonna look like this:
for(initialization; condition(your condition is your scan) ; increment/decrement)
{
statement(s);
}
3) you statement is going to be another scan, or as you refer to it as entering several numbers
If you want to use the numbers later you can save them in an Array. First you ask the user how big the array has to be (quantity). Then you initialize an Array with the user input size. You need to watch out that the number is positive. After that you make a for loop, that has the input quantity times of iterations. After each step you save the number in the proper spot. In the end you can output the numbers.
Validation of user inputs can be done with Regular Expressions. Here is a good tutorial on RegEx: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
import java.util.Arrays;
import java.util.Scanner;
public class VariableInputs
{
private Scanner scanner;
private String input;
private boolean isInputBad;
public VariableInputs()
{
this.scanner = new Scanner(System.in);
this.isInputBad = false;
}
public void startInteraction()
{
System.out.println(
"How many Integers would you like to enter? Enter a positive number that is smaller than 100.");
int quantity;
do
{
if (isInputBad) System.out.println("Enter a valid number."); // this gets printed if the user entered a wrong input (f.e. "abc").
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d{1,2}")); // this checks if the input contains only number 0-9. The input has to have atleast 1 and max 2 numbers.
isInputBad = false;
quantity = Integer.parseInt(input); // because of the regular expression we know for sure that the input string is a number. So we can parse it.
int[] numbers = new int[quantity]; // init array with input quantity.
System.out.println("Good job my friend. You have entered " + quantity
+ ". Go ahead and enter those numbers.");
for (int i = 0; i < quantity; i++)
{
do
{
if (isInputBad) System.out.println("Enter a valid number.");
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d"));
numbers[i] = Integer.parseInt(input);
isInputBad = false;
}
System.out.println("Good job my friend. You have entered " + quantity
+ " numbers.");
System.out.println("The numbers are: " + Arrays.toString(numbers));
scanner.close();
}
public static void main(String[] args)
{
VariableInputs vi = new VariableInputs();
vi.startInteraction();
}
}
You can try this code and see if its useful:
import java.util.Scanner;
import java.util.Arrays;
public class ScannerIn {
public static void main(String[] args) {
System.out.print("Please enter how many numbers (between 1 and 10)? ");
Scanner in = new Scanner(System.in);
int numbersCount = in.nextInt();
System.out.println(numbersCount);
if (numbersCount <= 0 || numbersCount > 10) {
System.out.println("Numbers count must be between 1 and 10. Exit program!");
System.exit(0);
}
int [] myNumbers = new int [numbersCount];
for (int i = 0; i < numbersCount; i++) {
System.out.print("Please enter your number: ");
in = new Scanner(System.in);
myNumbers[i] = in.nextInt();
}
System.out.println("Numbers input: " + Arrays.toString(myNumbers));
}
}
I'm in a university and I don't understand how to fix this problem. I'm trying to make a program where a user types in all the numbers s/he wants, and enter -1 when s/he is done. "Expected" results are as directed by my professor:
Write a program that will allow the user to enter any number of positive integers.
The user will enter a -1 when they are done entering numbers
(do not include the -1 as a number).
The program must print out, when the user is done entering numbers, the following:
Which number had the longest run of identical values, and how long the run was
The minimum number entered
The maximum number entered
For example, if the user enters these numbers:
5
9
5
7
5
7
-1
Then the program would print out:
Longest run: 5 entered 3 times
Minimum number: 2
Maximum number: 9
If there are multiple runs of equal length, print out the first such run encountered.
import java.util.Scanner;
public class ExSixNumber {
public static void main(String args []) {
int mostUsedNumber = 0;
int mostUsedCount = 0;
System.out.println("I will track all your numbers!");
System.out.println("Enter any digits between 1 and 9.");
System.out.println("Enter '-1' when done:");
Scanner scn = new Scanner (System.in);
while(scn.hasNext()) {
String userInput = scn.next();
while (scn.equals (userInput)) {
mostUsedNumber++;
mostUsedCount++;
}
if(userInput.equals("-1")) {
System.out.println("Your tracked data:");
System.out.println("Longest run: " + mostUsedNumber + " entered " + mostUsedCount + " .");
break;
}
}
}
}
This is as far as I had gotten. It doesn't like to track my userInput, could someone point me in the right direction on improving the program? I'm new and not asking for a direct answer, but "dummy" terms would be greatly appreciated. :)
hope this will help :)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class one {
public static void main(String args[]) {
int mostUsedNumber = 0;
int mostUsedCount = 0;
int maxNo=-1;
int minNo=-1;
List numberList = new ArrayList<Integer>();
List mostOccuranceList = new ArrayList<Integer>();
System.out.println("I will track all your numbers!");
System.out.println("Enter any digits between 1 and 9.");
System.out.println("Enter '-1' when done:");
Scanner scn = new Scanner(System.in);
while (scn.hasNext()) {
String userInput = scn.next().trim();
int user_input = Integer.parseInt(userInput);
if(maxNo==-1 && minNo ==-1){
maxNo=minNo=user_input;
}
if (user_input > 0 && user_input < 10) {
// returns the number of occurrences
int occurrences = Collections.frequency(numberList,user_input);
if (occurrences == mostUsedCount) {
mostOccuranceList.add(user_input);
} else if (occurrences > mostUsedCount) {
mostUsedCount = occurrences;
// emptying the most occurrence list since current input is the most frequent number
mostOccuranceList.removeAll(mostOccuranceList);
mostOccuranceList.add(user_input);
}
if(user_input>maxNo)
{
maxNo=user_input;
}
if(user_input<minNo){
minNo=user_input;
}
numberList.add(user_input);
}
mostUsedNumber+=1;
mostUsedNumber=Integer.parseInt(mostOccuranceList.get(0).toString());
if (userInput.equals("-1")) {
System.out.println("Your tracked data:");
System.out.println("Longest run: " + mostOccuranceList + " entered " + mostUsedCount + " .");
System.out.println("Maximum Number :- "+maxNo);
System.out.println("Minimum Number :- "+minNo);
break;
}
}
}
}