My program keeps terminating when it shouldn't. Why? [duplicate] - java

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 10 years ago.
Hey guys I was working on making a number averaging program and I wanted to insert this function that allows the user to enter the letter "y" to run again and do another computation, however, my program shows the terminated message (I'm using Eclipse) after the first computation, even though I want the user to be able to enter the input.
Here is the part of the source code that puzzles me:
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
System.out.print("This is an averaging program. How many numbers would you like to average together?");
int total=input.nextInt();
int i;
float sum=0;
for(i=0; i<total; i++)
{
System.out.print("Enter your numbers: ");
sum += input.nextFloat();
}
String y;
System.out.print("Your average is: " + sum/total + "\n");
System.out.print("Would you like to do another computation? Type y for yes, or something else for no.");
y=input.nextLine();

try this:
change
sum += input.nextFloat();
to
sum += input.nextFloat();
input.nextLine();
And
int total=input.nextInt();
to
int total=input.nextInt();
input.nextLine();
Explanation. You should manually read the newline character \n after reading a number form Scanner
Of course you should also add the relevant part of the program in a do while loop in order to execute repeatedly, but you probably know that.

Related

Scanner and User Input in Java Troubles [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I'm a student and I have been tasked to make a program that takes in the three sides of a triangle and outputs the angles of the triangle in reference to the sides. I haven't programmed the equation yet but I have been messing around with the Scanner and "if" statements to start the program. Already I have a problem:
--Here is the output of the beginning part of the program. But that is where it stops. I prompt the user to type a "D" or a "R" and it won't allow the user to type in that spot. However, earlier in the program I was able to prompt the user for a character. Can someone figure out why the previous prompt works and this one does not.--
This is the SSS Triangle program to find the angles of a triangle.
Do you know all the sides of a triangle but need to know the angles? (Y/N):Y
What are the lengths of the sides of your triangle?
-If all the same length then don't worry about the smallest, medium, and largest-
The length of the smallest side: 3
The length of the medium side: 4
The length of the longest side: 5
Would you like the angles in degrees or radians? (D/R):
--Here is the code. The last line is where I am having trouble--
public class SSSTriangle {
public static Scanner read= new Scanner(System.in);
public static void main(String[]args) {
System.out.print("This is the SSS Triangle program to find the angles of a triangle. \n Do you know all the sides of a triangle but need to know the angles? (Y/N):");
String response= read.nextLine();
if (response.contains("N")) {
System.out.println("Okay, have a good day!");
}
if (response.contains("Y")) {
giveMeTheSides();
}
}
public static void giveMeTheSides() {
System.out.println("\nWhat are the lengths of the sides of your triangle? \n -If all the same length then don't worry about the smallest, medium, and largest-");
System.out.print("The length of the smallest side: ");
double a = read.nextDouble();
System.out.print("The length of the medium side: ");
double b = read.nextDouble();
System.out.print("The length of the longest side: ");
double c = read.nextDouble();
if (a<=0||b<=0||c<=0) {
System.out.println("Nice try! Your given sides do not produce a possible triangle.");
}
else {
if ((a+b)<c) {
System.out.println("Nice try! Your given sides do not produce a possible triangle.");
}
else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse= read.nextLine();
Change the last else statement to read.next() and your code executes. You're simply looking to get a single String response so there is no need to grab the entire line from the Scanner:
else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse = read.next();//Change to read.next()
System.out.println("Your new response was " + newResponse); //Psuedo code to see if the output is correct.
}
Here is your last line of output:
Would you like the angles in degrees or radians? (D/R):
D
Your new response was D
The issue is that the program actually does read a line and then exits. It is finding something because when you read the last double, the user enters a newline character, but it is never read (because you are only reading the double). To get around this you can simply read in another line (with the extra newline character) after the nextDouble(), in addition to your current nextLine().
System.out.print("The length of the smallest side: ");
double a = read.nextDouble();
System.out.print("The length of the medium side: ");
double b = read.nextDouble();
System.out.print("The length of the longest side: ");
double c = read.nextDouble();
read.nextLine(); // Discard the extra newline
if (a<=0||b<=0||c<=0) {
...
else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse= read.nextLine();

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);

Java program makes user enter same input twice to run after initial input error

I am having problems with my program. Everything is running smoothly, however, when the user inputs the wrong variable it does display the right feedback, but the user then has to enter one extra variable than previously stated.
Maybe it's a simple mistake I have made, but I can't see it..
It's confusing. An example when I run the program:
How many grades would you like to average?
3
Please enter 3 grades:
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number:
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3
Your average is: 96.67
The second 100 input in the console should not appear, but it does when the user has at least one input error. If I were to run the program and input all the correct variables, then the program works smoothly.
This error also occurs when asking for how many grades the user would like to average. I thought it'd be easier to view what's wrong with my program by the second part.
I'm trying to get this program to run smoothly. Help is appreciated!
for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
// Check if the input variables are numerical variables
while (!input.hasNextDouble()) {
input.next();
System.out.println("You've entered a non-numerical variable. Please enter a number: ");
while (input.nextInt()<= 0){
System.out.println("You've entered a negative number. Please eneter a positive number: ");
}
}
// Read grade input
gradesInput = input.nextDouble();
Instead of input.hasNextDouble() you can try below
Scanner scan = new Scanner(System.in);
System.out.print("Enter total no of input ");
int total = Integer.parseInt(scan.nextLine());
int[] input = new int[total];
for (int i = 0; i < total; i++) {
while (true) {
try {
System.out.print("Enter number ");
String in = scan.nextLine();
input[i] = Integer.parseInt(in);
break;
} catch (RuntimeException re) {
System.err.print("Invalid input. ");
}
}
}
scan.close();
System.out.println(Arrays.toString(input));
It'll force the user input only numbers, you can add boundaries or change data type if required.

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

Java: Trouble taking user input

and while trying to make this simple program, im having trouble getting user input in terms of the string. When entering the integer, im having no problems, but when my program asks the user to enter another a character, the cursur will blink waiting for me to type in something, but it wont let me. If i comment out all of the integer stuff, i am then allowed to enter a string. Is there a reason i cant input both? thank you
import java.util.Scanner;
public class math {
public static void main(String args[]){
int int1,int2,int3;
String operator;
Scanner ahmad=new Scanner(System.in);
System.out.print("Enter three integers: ");
int1=ahmad.nextInt();
int2=ahmad.nextInt();
int3=ahmad.nextInt();
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
System.out.println("Thank you");
}
}
nextInt() only consumes the integer, it doesn't consume the whitespace characters (EOL in this case). Use two nextLine(), one to consume the EOL character, one to prompt you for input.
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
operator=ahmad.nextLine();
System.out.println("Thank you");

Categories