I'm trying to create a simple application that takes in a certain number of names and creates tournament brackets from them. Right now I'm stuck creating the number of matches and contestants per match. As it stands, I want to create a failsafe that will warn the user if the number of people they want in a match does not divide evenly with the total number of people. I ask them to simply enter either 'Y' or 'N' to dictate this. The problem is that the program does not give them the chance to enter their response and automatically spits out a NoSuchElementFound exception: No line found.
This is a brand new scanner made to take in this response. I tried using .hasNext in order to see if there is no next line, and the result it gets is false. Essentially, after I've gotten all of the contestants (a separate method that works fine) this is the console:
Total Number of Contestants: 5
How many contestants do you want to compete per match?
2
Warning: Choosing this number means that there will not be the same number of contestants in each match.
Reminder that the total number of contestants is: 5
If you want to proceed, enter 'Y'. If you want to enter a different number of contestants per match, enter 'N'.
check value: false
If it helps, this is the troublesome code:
String answer = "yes";
Scanner scan = new Scanner(System.in);
float roundedMatchCount = 0;
float matchCount = 0;
entrant victor = new entrant();
float matchMembers;
Scanner scan = new Scanner(System.in);
System.out.println("How many contestants do you want to compete per match?");
matchMembers = scan.nextInt();
matchCount = input.size() / matchMembers;
scan.close();
Scanner s = new Scanner(System.in);
if (input.size() % matchMembers !=0)
//if the number of contestants is not divisble by the number
//of participants in a match
{
System.out.println("Warning: Choosing this number means that there will not be the same number of contestants in each match.");
System.out.println("Reminder that the total number of contestants is: "
+input.size());
//begin while
System.out.println("If you want to proceed, enter 'Y'. If you want to enter a different number of contestants per match, enter 'N'.");
boolean check = s.hasNextLine();
System.out.println("check value: " + check);
answer = s.nextLine();
//WHAT
if (answer.contains("N"))
{
//ask for a new number
}
else if (answer.contains("Y"))
{
//round the number of matches up or down depending on user input
}
else
{
System.out.println("Error: Invalid response.");
}
}
Please note that input is an ArrayList that was passed into this method from the previous one. I know that the correct number of entries is inside it because in previous tests I had its contents and size printed out.
As KDM helpfully pointed out, my issue was being caused by how I closed the previous scanner. Getting ride of scan.close() solved my problem.
Related
I am currently working on Java code. Basically, the int input works. However, if I type in a character, the whole system crashes. My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.
do {
System.out.println("How many players would like to participate in this game?\t(2-4 players)");
numberOfPlayers = in.nextInt();
} while(in.hasNextInt());
numberOfPlayers = in.nextInt();
I personally prefer to use a while loop for this sort of thing rather than the do/while. Not that there is anything wrong with the do/while, I just feel it's more readable to use the while loop.
I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry. It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.
You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:
Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";
while (userInput.equals("")) {
// The Prompt to User...
System.out.print("How many players would like to participate in this game?" + ls
+ "2 to 4 players only (q to quit): --> ");
userInput = in.nextLine();
// Did the User enter: q, quit (regardless of letter case)
if (userInput.toLowerCase().charAt(0) == 'q') {
// No, the User didn't...
System.out.println(ls + "Quiting Game - Bye Bye.");
System.exit(0); // Close (exit) the application.
}
/* Did the User supply a string representation of a numerical
digit consiting of either 2, 3, or 4. */
if (!userInput.matches("[234]")) {
// No, the User didn't...
System.out.println("Invalid input! You must supply a number from 2 to 4 "
+ "(inclusive)." + ls + "Try again..." + ls);
userInput = "";
continue; // Loop again.
}
// Convert numerical string digit to an Ingeger value.
numberOfPlayers = Integer.parseInt(userInput);
}
System.out.println(ls + "The Number of players you provided is: --> "
+ numberOfPlayers);
You will notice that the Scanner#nextLine() method is used to accept User input as a String. This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User. To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]". What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4". Anything else other than any one of those three digits will display this message:
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...
and, force the User make yet another entry.
I have a problem I sort of half fixed? It's more of a logic error, I think. My program overall is running smoothly, but I need to fix the flow of how my program interprets user input.
This program should report user error if they input a non numerical value or a negative number. And if the user enters 0, then is should accept it as a correct answer ( I have yet to figure out how to do that since my condition is whether or not it's a double).
I'm trying to differentiate between whether the user inputs a negative number or a character in the feedback. So far, I've made a loop to continuously prompt the user to enter a number if they don't input a double. Though I'm not sure how to go about accepting a 0 as an answer and filtering out negative numbers. I went back to my flow diagram and figured I may need to use an if-else statement to do this. But how can I do that while keeping the loop going? I'm not totally sure how I'm suppose to format that kind of thing.
Help is appreciated for this newbie! Thank you!
while(looping){
// Prompt user to enter how many grades they want averaged
System.out.println("How many grades would you like to average? ");
// Check if the input variables are positive numerical variables
// Or else report to user to input a number
while(!input.hasNextDouble()) //cannot be negative
{
input.next();
System.out.println("Please enter a number: ");
}
gradeNumber = input.nextInt();
// Prompt user to enter the grades
System.out.println("Please enter " + gradeNumber + " grades: ");
// Use a for-loop to control how many loops - reference to gradeNumber
for(gradesCount = 0; gradesCount < gradeNumber; gradesCount++){
// Check if the input variables are numerical variables
while (!input.hasNextDouble())
{
input.next();
System.out.println("Please enter a number: ");
}
gradesInput = input.nextDouble();
finalGrades = finalGrades + gradesInput;
} // end loop
I have an assignment to make a program which allows the user to enter an unlimited
set of numbers until 0 is entered, to print the smallest and largest number, and to say if they are odd or even.
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Please note I only began learning Java last week and so am unfamilliar with the language
Many thanks!
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Since this is a homework, and you probably do not want us to do your homework for you. This is what you can do:
do{
//prompt user for input
//prompt user to continue (y/n)
//if 'n' was given
//proceed = false;
}while(proceed);
You can use a do-while or while loop. You can now prompt user for input infinitely till they decide to stop.
Update 1: (According to changes in question)
Terminating condition: when 0 is received as input:
do{
//prompt user for integer input
//if (input == 0)
//break; (exit loop)
//store input
}while(input != 0);
***Try to do it on your own.Use this for reference only.
I know its not right to give away the code as it is for your assignment.Just use (understand and learn)this if you didn't get the output.
int n=0,temp=0,z=0,i=0,j=0;
int []a=new int[1000]; //as size is not given by user assign the array with a much greater value
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Object for BufferedReader class used for reading elements
do{
System.out.print("Enter the number:");
a[n]=Integer.parseInt(br.readLine()); //String to integer conversion
n++;
System.out.println("Do you want to enter more numbers(0/1):");
z=Integer.parseInt(br.readLine());
}while(z!=0);
//Sorting
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
//Now after sorting the smallest number will be in the first location ie;
//"0" so inorder to check it is even or odd we take check its remainder when it is divided by 2.
if(a[0]%2==0){
System.out.println("The smallest number is : "+ a[0] + " & the number is even");}
else{
System.out.println("The smallest number is : "+ a[0] + " & the number is odd");}
if(a[n-1]%2==0){
System.out.println("The largest number is : "+ a[n-1] + " & the number is even");}
else{
System.out.println("The largest number is : "+ a[n-1] + " & the number is odd");}
A sample output is as follows :
I am brand new at Java and this one is throwing me. Using the below code it loops through for the first question until I enter anything but an integer but after finishing that loop it does not stop for the remaining question.
Through a bit of research and reading I have found that I need to use the in.nextLine() to eat the newline character after the input. However no matter where I place the nextLine() it doesn't work? I thought it would be after the first int input = in.nextInt(); line but that did not work. Any help on where it would go and why?
System.out.print("How many CUs per course are remaining in your degree program? Enter any letter to quit: ");
while (in.hasNextInt()) { // Verify input is an integer
int input = in.nextInt();
if (input <= 0) // Verify that input is not negative or zero
{
System.out.println("Please enter a positive number or any letter to quit");
System.out.print("Add another course or any letter to quit: ");
} else {
courseCuList.add(input);
System.out.print("Add another course or any letter to quit: ");
}
}
System.out.print("How many CUs do you plan to take per term?");
while (in.hasNextInt()) {
int input = in.nextInt();
// in.nextLine(); This line consumes the \n
if (input <= 0) {
System.out.println("Please enter a whole positive number.");
System.out.println("How many CUs do you plan to take per term?");
} else {
cuPerTerm = in.nextInt();
}
}
Your problem is that in while (in.hasNextInt()) each call of hasNextInt needs to wait for user input, and then test if it is integer or not.
So each time user give integer, condition will be evaluated to ture, loop will execute and condition will need to be checked again, and if it is integer loop will execute again. This will go again and again until hasNextInt will be able to return false, for instance when user will give non-integer - like letter. But in this case condition in next loop will also return false because this non-integer value was not consumed after first loop. To let second loop work you would need to invoke nextLine two times
to consume line separator after previously put correct integer
to consume actual non-integer value
But this may also fail if user will not put any integer before non-integer value because there will be no line separator to consume.
So consider changing your logic to something similar to
boolean iterateAgain = true;
System.out.print("give me positive number: ");
while (iterateAgain) {
// this inner loop will move on only after getting integer
while (!in.hasNextInt()) {//here program waits for user input
in.nextLine();// consume non-integer values
System.out.print("that wasn't positive number, try again: ");
}
int number = in.nextInt();// now there must be number here
in.nextLine();// consume line separator
if (number > 0) {
System.out.println("you gave " + number);
// do what you want with this number
iterateAgain = false;// we can leave loop
} else
System.out.print("that wasn't positive number, try again: ");
}
If you want to execute next loop then all you need is reset iterateAgain value to true.
You need to read twice.
The exit condition on your while loop is hasNextInt() - checking to see if the next token is an integer doesn't actually clear that token, which means that the next nextLine() is going to read the token, and the subsequent nextLine() will read the newline character.
To demonstrate this, place the following between the loops:
System.out.println(in.nextLine() + " | " + in.nextLine());
For the input 4, 4, A, you will see the output:
How many CUs per course are remaining in your degree program? Enter any letter to quit: 4
Add another course or any letter to quit: 4
Add another course or any letter to quit: A
| A
How many CUs do you plan to take per term?
There are two tokens that need to be cleared from the buffer, and neither of them are integers. Because of this, no matter where you put nextLine(), it will fail - you need to insert it twice. If you only insert it once, the next token won't be an integer, and hasNextInt() will fail when the program tries to enter the second loop.
In order to get your program to work, simply insert:
in.nextLine(); in.nextLine();
before the second loop. (Note that you shouldn't put both this and the print-out in, as this will read four times.)
I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}