Unlimited number of user inputs - java

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 :

Related

Creating a game with loops that compares a secret number to user input

I was asked to create a mastermind game for school. The project never ran properly and I believe I went about the process in the wrong way. While the assignment is already past due I would like to know where I went wrong. Keep in mind we have still not gone over arrays.
This was the assignment description:
Your program will choose a random 4 digit number as the secret number. Your program must prompt the user to enter a 4 digit number as their guess. The program will respond with a message indicating how many of the digits in the user’s guess are the same as the digit in the same position in the secret number. For example, if the secret number is 3749, and the user’s guess is 9753, then the program would respond with the message You matched 1, because only one of the digits (the 7) in the user’s guess is the same as the digits in the same position in the secret number. The program will allow the user to continue to enter guesses until they guess the correct secret number. After the user has entered the secret number, the program will output a count of the total number of guesses the user took to find the secret number. Then the program will ask the user if they would like to play again. If the user answers “yes”, then the program will choose another random 4 digit number and play continues as described above.
Where was the best place to start for this assignment?
What was the best way to use loops?
How do I select different parts of the secret number?
Any help I can get now will help me catch up in the class.
import java.util.Scanner;
public class Assignment04 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("----- MASTERMIND -----");
System.out.println("Guess the 4 digit number!");
int secretNumber = (int)(Math.random() * 1000 + 1);
int usersGuess = 0;
int counter = 0;
int guessCount = 1;
for(int i=0; i<guessCount; guessCount++) {
System.out.print("Enter your guess: ");
usersGuess = in.nextInt();
if (String.valueOf(usersGuess).substring(0,0)==String.valueOf(secretNumber).substring(0,0));
{
guessCount ++;
counter ++;
break;
if (String.valueOf(usersGuess).substring(1,1)==String.valueOf(secretNumber).substring(1,1));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(2,2)==String.valueOf(secretNumber).substring(2,2));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(3,3)==String.valueOf(secretNumber).substring(3,3));
{
guessCount ++;
counter++;
break;
}
System.out.println("You matched " + guessCount);
if(counter==4);
{
System.out.println("Congratulations! You guessed the right number in " + counter + "guesses");
System.out.println("Would you like to play again? (Yes/No)");
}
}
}
}
}
This is all I was able to come up with.
So few points
Your for loop condition (i < guessCount) shouldn't be driven by the guess count because it should continue looping until they guess correctly.
You'd maybe want e.g. a boolean named "continueLooping" which is true and a while condition evaluating that instead of a for loop.
If the guessCount (which is summing the number of times the correct digits were aligned) is 4 then "continueLooping" would be set to false if the user said "No" when asked "Would you like to play again?"
You shouldn't be breaking after each matched digit. What if the first digit matches and the second digit matches? The break after the first match will stop the second digit ever being counted and the loop will exit
You want to check the length of their input to make sure it's 4 digits long
You'd want to use .equals() method of String rather than == as String is a reference type meaning equality is checked using equals() not the "==" operator (that is for checking primitive equality or exact reference equality)
Your "counter" should only increment once at the beginning of every loop
You GuessNumberRandomizer is wrong: it will produce 3 digit numbers only. Use this for 4 digits:
int secretNumber = (int)(Math.random() * 10000 + 1);
Also, I would suggest using String input or better yet, parse the integer input to String and use charAt() method for comparison instead. Also your usage of break may create some errors if more than 1 one digit was guessed correctly.
The first loop is is not really a good case scenario for a for loop. You should use a while loop. While will continue iterating, possibly infinitely, until the condition on which it's evaluated is no longer true.
Since your program should continue until the user guesses, or until he guesses right and doesn't want to play anymore, you should have a boolean "flag" which tells the game it should continue the loop. If the game has been won (when the correct guesses in a turn is equal to 4) then you should prompt the user if they want to continue playing, and if they say no, you just turn off the flag and the program exits.
Something like this
boolean continue = true;
int correctGuesses;
int numberOfTimesAttempted = 0;
while(continue){
numberOfTimesAttempted++;
correctGuesses = 0;
//Your game logic
if(correctGuesses == 4){
System.out.println("Do you wish to continue? Y or N");
char answer = sc.nextLine();
if(char.toUpper('N'){
continue = false;
System.out.println("It took you " + numberOfTimesAttempted + "to win!");
}
}
}
As some users pointed out, you should also have logic to verify that the user enters strictly 4 numbers.
Rather than comparing each number individually, simply convert the number to a char array and create a for loop that iterates through it. if the char at the current index is equal to the one in the secret number, increase the number of guess counts.
At the end of each loop, print the number of correct guesses. If number of guesses is 4, the user wins.

How to reverse a number in java in a user generated program

My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.
import java.util.Scanner;
public class reverseInt3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int reverse = 0;
int number2;
int reverse2 = 0;
char repeat;
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
System.out.println("Reverse of entered number is "+reverse);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
while( repeat == 'Y' || repeat == 'y')
{
System.out.println("Please enter your new set of numbers");
number2 = keyboard.nextInt();
keyboard.nextLine();
while( number2 != 0 )
{
reverse2 = reverse2 * 10;
reverse2 = reverse2 + number2%10;
number2 = number2/10;
}
System.out.println("The reverse of entered number is "+reverse2);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
}
}
}
First let's talk about your problem:
If the user input goes beyond the bound of int, long or double your program provides a negative reverse.
That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.
If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.
I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.
Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:
It's obvious that you've repeated these part of codes:
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
and
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
and
System.out.println("Reverse of entered number is "+reverse);
If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).
Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?
Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.
Hope this helps.

Sentinel number in if statement

For data structures and algorithms in java class I've been assigned to create a program that takes user input for an item's name and price and then averages the price. I have successfully done that, however, I am having a great deal of trouble on a certain specification for the program: a sentinel number (-1) that terminates the project. Here is my code, I will explain what the issue is after.
while(true){
System.out.print("Enter item " + (count + 1) + " name: "); // enter name
names[count] = in.next(); // next string becomes count index
System.out.print("Enter item " + (count + 1) + " price: "); // enter price
prices[count] = in.nextDouble(); // stores price entered as array index
if(prices[count] == -1) break; // if next price == -1 // the code i want to change.
if(names[count].equalsIgnoreCase("peas")) flag = true;
average += prices[count];
count++;
}
So, my issue is: I want to terminate the program when I enter -1 for the item name, not have to enter a "dummy" item name and then have to enter the sentinel number (-1).
Sorry for the long explanation, just trying to be thorough.
Thanks for taking the time to read this and help a programmer hopeful out.
You need to use a String for your comparison (but "-1" will do). Also, do it immediately after you get the input. Something like,
names[count] = in.next();
if (names[count].equals("-1")) {
break;
} // ...

My scanner doesn't have a next line, causes a NoSuchElementFound exception

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.

Get user to input integers

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

Categories