Scanner and User Input in Java Troubles [duplicate] - java

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

Related

java program how add a function that goes back code if player has inputted it wrong

I have a problem with my program is not with the code is how I am going to do it that's the confusing part that I am stuck with. just to let you know I am a basic java coder I do not understand complicated stuff so bear in mind that my code isn't the best.
----------------------------------------------------------- program explaintion-----------------------------------------------------------------
let's get into the point of explaining how it works before I show you my problem, ok when you execute the program it prompts you a sort of like a menu in a video game but it's a text-based, it shows you different options like enter player details, play the math game show score and then quit. enter player details it tells player 1 to enter he/she name and then tells another one to input he/she player name then prompts you back to the menu. play the math game is where a player 1 is asked to input he/she math equation after that player 2 has to solve it if he gets it right he gets 10 points if no the player gets no points at all. then repeats for another player to input he/she math equation then prompts you back to the menu. show scores it shows who got the most scores in the math game it calculates who's got the most if both of them got the same score then means a tie then prompts you back to the menu. and the last thing the quit option when you choose that option it stops the program. if the player chooses a wrong choice he gets an error message and puts you back to the menu
ok here is the first class called menu and other class which is connected with menu called game factions
menu:https://gist.github.com/LOLMEHA/86ff28b038d85030e346785e953644e0
gamefactions:https://gist.github.com/LOLMEHA/f05a51e07c8823a0e65cebbf81cc52ef
so this section of code that I have trouble fingering it out myself
import java.util.*;
public class Gamefunctions // this is a core when player choosess one of these options from the menu
{
String[] player =new String[2];
double scorea = 0; // verribles of all the objects
double scoreb = 0;
int i;
Scanner input = new Scanner(System.in);
double answer = 0;
double numA, numB;
char operator;
char operator2;
boolean quit = false;
double sum1;
double sum2;
public void enterDetails(){ // if player select enter details
for ( i=0;i<2;i++) {// tell's player to input he/she's name and stores them
int c=i;
System.out.println("Welcome to the maths quiz game please input player name "+c++);
player[i] = input.next();
}
}
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
if () {
if (operator == '+') {// this is if operator is one of these like +-*/^ and then it works out the sum
answer = numA + numB;
}
if (operator == '-') {
answer = numA - numB;
}
if (operator == '*') {
answer = numA * numB;
}
if (operator == '/') {
answer = numA / numB;
}
if (operator == '^') {
answer = Math.pow(numA, numB);
}
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
System.out.println("");
System.out.println(player[1]+"\t solve the equation"); // tells other player to slove the equation
sum2 = input.nextDouble();
if (sum2 == answer){// checks if the answer from the player is good or not if its good he/she gets 10 points if he/she gets it wrong gets no points and shows the right answer so the player learns from his/she mistakes
scoreb = scoreb + 10.00;
System.out.println("correct you got 10 points to your score");
System.out.println("");
} else{
System.out.println("incorrect you got no points the correct answer was:"+"" + answer);
}
you know when the program ask to player to input his math eqtion and outputs this and continues with the program and waiting for the user to input
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
let's say that the player inputs like this 10+10 enter but it will not work since they are stored in numA which is an int, I want to make a error message saying that you can not input like this 10+10 you have to input like this 10 enter + enter 10 enter so it will be able to work
if the player inputs it correctly it will continue the program
so if you have any problems with my explaintion of my plroblem pls ask so I can edit it thank you for time :)
Here’s the bit of your code I’m going to be looking at:
String s = input.next();
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
First up, a couple nitpicks: Java is not C. You don’t need to declare all your variables at the beginning of your code blocks. numA, numB and operator are never used outside this bit of code, so it makes sense to declare them in here as well.
You’re also using input.next() with Double.parseDouble() once, then input.nextDouble() the next time. Stick to one or the other, it’ll make debugging easier if something doesn’t work properly.
And finally, what happens if someone enters 10 +1 0? The error is silently ignored because the 1 gets picked up as part of the operator string then discarded by charAt(0). A more resilient parsing method here would be to fetch the entire String first, then check for length == 1 before calling charAt(0).
double numA = input.nextDouble();
String operatorString = input.next();
char operator;
if (operatorString.length() == 1) {
operator = operatorString.charAt(0);
} else {
// Handle error
}
double numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
Onto your question then: how do we detect an invalid input? Take a look at the documentation for Scanner#nextDouble() (emphasis mine):
public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
So we know nextDouble() can detect the invalid input for us. It does this in the form of an exception, which we can listen for (or catch) using a try ... catch statement:
try {
double numA = input.nextDouble();
} catch (InputMismatchException e) {
System.err.printf("Invalid input! Expected number, found '%s'.\n", input.next());
}
We could extend this and wrap the entire section of code in a single try ... catch, but then the user would have to start again if they make one mistake. A more user-friendly solution would be this:
double numA;
while (1) {
try {
numA = input.nextDouble();
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected number, found '%s'.\n", input.next());
}
}
Note the even if you don’t print it, the call to input.next() is necessary to prevent an infinite loop.
Now we just need to do something similar for operator:
char operator;
while (1) {
String operatorString;
try {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
operator = operatorString.charAt(0);
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected character, found '%s'.\n", operatorString);
}
}
This seems very similar to the previous snippet for a number - let’s try to refactor some of the common code here into a method:
#FunctionalInterface
public interface ScannerGetter<T> {
T apply() throws InputMismatchException;
}
public <T> T getValueFromScanner(ScannerGetter<T> getter, String type) {
while(1) {
try {
return getter.apply();
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected %s.");
}
}
}
There’s a lot going on in these few lines. The first part declares a functional interface - this is a basically a custom type of lambda function. We’ll come back to that in a moment.
The method itself (getValueFromScanner()) is a generic method. It allows us to use the same method with different types in place of the generic parameter (T) without duplicating it.
This is how you’d use the above method to retrieve your three inputs:
double numA = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
char operator = this.<Char>getValueFromScanner(() -> {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
return operatorString.charAt(0);
}, "operator");
double numB = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
// Once your code gets here, all three variables will have valid values.

How to multiply a set number and a user input number in Java?

I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));

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 while loop terminates after one interation with scan.nextLine(); method

I am a beginning Computer Science student and currently stuck with one problem.
It's a simple program that asks the user for a number x, then solves a Polynomial equation for that number. Afterwards, it is supposed to ask the user if he wants to continue, and if so, a new number for x is prompted. However, this program only asks the user for x once, and then terminates after evaluating the Polynomial. It even prints Continue? but doesn't even wait to read in the next line, it seems to terminate right after. It seems to ignore response = scan.nextLine(); completely.
Goal of this problem was to learn how to use while loops and Scanner.
Can anybody see my mistake and give me a hint?
Thank you!
import java.util.Scanner;
class EvalPoly
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double x; // a value to use with the polynomial
double result; // result of evaluating the polynomial at x
String response = "y"; // yes or no
while ( response.equals("y") )
{
// Get a value for x
System.out.println("Enter a value for x:");
x = scan.nextDouble();
// Evaluate the polynomial
result = (7 * x * x * x) - (3 * x * x) + (4 * x) - (12);
// Print out the result
System.out.println("The result of the polynomial at x = " + x +" is: " + result + "\n");
// Aks user if the program should continue
// The users answer is "response"
System.out.println ("continue (y or n)?");
response = scan.nextLine();
}
}
}
nextDouble() just reads the double, not the end of the line that double was written on - so when you next call nextLine(), it reads the (empty) remainder of that line, which isn't equal to "y", so it breaks from the loop.
Putting nextLine() straight after the nextDouble() call should fix it by consuming the rest of this empty line.
Watch out for this when using nextDouble() or nextInt() - it's a classic mistake that's often made!
Use
x= Double.parseDouble(scan.nextLine());
Instead of
x = scan.nextDouble();
This happens because when you key in the number and press "Return" the nextInt only takes the integer entered, therefore the "Return -End of Line" is still part of the line, which is assigned to your response variable, and evaluated in the while loop, and fails cause it is not equal to 'y'. The solution is to skip a line before reading the response.
System.out.println ("continue (y or n)?");
scan.nextLine();
response = scan.nextLine();

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

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.

Categories