Dice Rolling Game - java

So in this dice rolling game, what the user inputs must follow the format of xdy, where "x" is the number of dice and "y" is the number of sides the dice has. If the input doesn't follow the format, the program should ask the user to put in another input.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("Please enter the number and type of dice to roll in the format <number>d<sides>.");
input = user_input.nextLine();
while()
{
System.out.println("Input is not valid. Please enter a new input");
input = user_input.nextLine();
}
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(5);
My question is, how do I make the while loop check for a character between two integers?

One elegant way to do this would be with a Pattern:
Pattern p = Pattern.compile("\\d+d\\d+");
input = user_input.nextLine();
while (!p.matcher(input).matches) {
System.out.println("Input is not valid. Please enter a new input");
input = user_input.nextLine();
}

Separate numberOfSides and number OfDice into two variables and then do whatever you want with them.
String input="6d3";
int numSides=Integer.parseInt(input.split("d")[0]);
int numDice=Integer.parseInt(input.split("d")[1]);

Related

How to validate input type(java) [duplicate]

This question already has answers here:
How to verify that input is a positive integer in Java [closed]
(3 answers)
Closed 15 hours ago.
I have the following snippet of code and I don't know how to make sure that the user is entering a positive int. What can I do so that the code makes sure the input type is valid.
public static void main(String[] args)
{
//creates a scanner
Scanner output = new Scanner(System.in);
//declare all the variables
int fours;
//ask the user how many fours they have
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
I tried using a do while loop like shown below, but it only makes sure that the input is greater than or equal to zero, but does not make sure it is an int.
do
{
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
while(fours <= 0 );
You can check Scanner#hasNextInt:
Scanner sc = new Scanner(System.in);
System.out.println("How many 4's do you have");
while (!sc.hasNextInt()) {
sc.next(); // skip the invalid input
System.out.println("Please enter an integer");
}
int fours = sc.nextInt();

Solved!: the for loop in my code won't repeatedly repeat, gather input, and put it into an array

I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}

How to make the scanner understand the amount I write?

This is just some homework but I cannot find a way to achieve it like I want. Have a look at my code please.
Once the numbers are typed, I'd just like to play around with them.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//user says if he'd like to use 3 numbers for instance (2,4,5)
System.out.println("How many numbers would you like to use? : ");
int amountOfNumbers = sc.nextInt();
System.out.println("Great! Please type in your numbers: ");
int numbers =sc.nextInt(amountOfNumbers);
// should let him write the amount of numbers he entered
}
Once he has typed the amount of numbers he'd like to use, I would like the scanner to give him the possibility to type in all of those numbers.
Let's say he the amount of numbers he'd like to use is three.
I would like him to be able to type it in the console like this:
First number + enter key
Second number + enter key
Third number + enter key
Not able to write anymore
That is what I meant here by adding "amountOfNumbers" in the scanner itself... (which is not working)
int numbers =sc.nextInt(amountOfNumbers);
BR
Consider a for loop:
for(int i = 0; i < amountofNumbers; i++){
// add to a collection / array / list
}
And then access what you need from there.
import java.util.*;
class EnterNumber{
public void enter_list_function(){
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers would you like to use?");
//Enter the Numbers of amount
int input = sc.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Great! Please type in your numbers: ");
//Input - Numbers of amount
for(int j =1; j<=input; j++ ){
int addval = sc.nextInt();
//Add the enter amount in array
list.add(addval);
}
Iterator itr=list.iterator();
while(itr.hasNext()){
//get the enter amount from list
System.out.println(itr.next());
}
}
public static void main(String[] args){
EnterNumber EnterNumber = new EnterNumber();
EnterNumber.enter_list_function();
}
}

How can i input several integer or another types?

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));
}
}

Java: Using scanner to read in boolean values failing.

import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}

Categories

Resources