Get user to input integers - java

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

Related

Java, How do I validate input when using scanner?

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.

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.

Unlimited number of user inputs

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 :

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

Why isn't the nextInt() method working?

I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.

Categories