Java while loop terminates after one interation with scan.nextLine(); method - java

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

Related

Keep asking for number and add and keep a counter and exit if entered letter Q

I dont know why its not working, the goals is have the program loop and keep asking you to enter a number and quit when its you enter Q. Whiles its looping it should add the numbers inputed and keep track the amount of times the number is inputted. When the user enters Q the program should exit and print the average
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner scn = new Scanner(System.in);
double counter = 0;
double total;
System.out.print("Enter a number: ");
String testString = scn.next();
while(!testString.equalsIgnoreCase("q")){
double number1 = Double.parseDouble(testString);
total = number1 + testString;
System.out.print(number1);
++counter;
scn.hasNextDouble();
}
}
}
Ok there are a few things in your code that are incorrect. Inside of your while loop you use scn.hasNextDouble this isn't doing anything to help your code make its way through the while loop. Since you are checking testString for your while loop I suggest updating testString like you did in the beginning of the code.
Also the line total = number1 + testString; doesn't make any sense and you should check out https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for more info on primatives.
Im unsure on why you are throwing a FileNotFoundException you are using standard system input(keyboard) and dont need to use that
Yep, you need a loop to continuously check the code. Basically, the program reaches the if statement and checks whether it's true for the moment or not. It is not true, as you haven't entered the letter q yet. So, the program just skips over the if statement, and ends itself.
As #Elliott Frisch mentioned, you need to update testString inside your loop.
The part that repeats itself starts with the while's { and ends with the closing }.
So you are not repeating
String testString = scn.next();
Try putting that line inside your while loop.
String testString;
while(!testString.equalsIgnoreCase("q")){
testString = scn.next();
double number1 = Double.parseDouble(testString);
total = number1 + testString;
System.out.print(number1);
++counter;
}
Now you'll keep grabbing stuff as long as it's not 'q'.
To improve that, it would be better to change your guard on the while loop to:
while (!scn.hasNextDouble()) {
// blah blah
}
That way it keeps reading until it finds something that doesn't match Double, so any letter will stop it.
Also better would be to use scn.nextDouble() instead of scn.next(), as that way you can be sure to get Doubles, and you don't need to check for 'q', and you don't need to parse the String.
while (scn.hasNextDouble()) {
Double number = scn.nextDouble();
total = total + number;
counter++;
}

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

Java -- How to make a continous counter (1 + 2 = 3; + 3 = 6) etc

I'm not sure if this is possible in Java. I just finished Python and I've taken a webdesign course, so my brain isn't synced with Java yet.
I want it to be something like this
double yourInput = input.nextDouble();
double numCount = (numCount + yourInput);
For example, if I entered 2, 7, and 9 (it would loop) I would want it to do something like this: numCount = 0; then numCount = 0 + 2; then numCount = 2 + 7; then numCount = 9 + 9.
Is this possible in Java? If so, how?
Just loop using input.hasNextDouble():
//give default value
double numCount = 0;
//while user is still giving input
while(input.hasNextDouble()) {
//get input
double yourInput = input.nextDouble();
//add input
numCount += yourInput;
}
//output
System.out.println("total = " + numCount);
Algorithm CONTINOUS_COUNTER()
BEGIN
DECLARE inputReader : java.util.Scanner(System.in);
DECLARE numCount : Double;
SET numCount := 0.0; //Setting the default value to the counter;
LOOP until inputReader.hasNextDouble() returns TRUE
numCount := numCount + inputReader.nextDouble();
END LOOP;
print "Num count = " + numCount;
END;
Dear Katy, this is the logic you should use to develop this program. This is just an algorithm. I don't think it's good to post the real program here, since you are learning Java. Try to convert this algorithm to the Java code. Learn it. :)
Here a working example:
import javax.swing.JOptionPane;
public class DoubleCounter {
private static double total = 0.0;
public static void run(){
while(true){
String input = JOptionPane.showInputDialog("Total Count: "+ total+" add next double: ");
try{
double next = Double.parseDouble(input);
total+=next;
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null, "Wrong input! You must get a valid number!");
continue;
}
}
}
public static void main(String[] args) {
DoubleCounter.run();
}
}
You define a class DoubleCounter with a static member total count.
This class has a run() method that infinitly loop and show ad InputDialog.
The input dialog alway return a string that we 'try' to parsed in a double.
If parsed without problem, we add the result to the total count.
The class has a main method that is the application entry point that 'statically' call run() method of DoubleCounter.
I suggest you to see how 'static' modifier work on class member (total) and on methods (run()).
Hope helped you!
Katy, this is the real program.
import java.util.Scanner;
public class ContinousCounter{
public static void main(final String [] args){
double numCount = 0.0;
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the values : ");
while(inputReader.hasNextDouble()){ numCount += inputReader.nextDouble();}
System.out.printf("The value for numCount = %f",numCount);
}
}
In order to do what I think you're saying here, you should be using a while loop. It is fairly simple, just think about how you want it to work. It will loop a block of code that adds the scanner's next line to a sum
double mySum = 0;
while(input.nextDouble() != 0){
double myInput = input.nextDouble();
mySum += myInput;
}
In the above loop, we are assuming that when the scanner's next line is 0 there are no more numbers to add, but that can be adjusted so that it stops at other times.
I can see that since you have completed a course in Python programming that you are able to come up with the logic for this and are only looking for convention or proper syntax, so let's explain how the above works:
A while loop will run as long as the statement you let it handle evaluates to true, if you want it to do something while false you can put use an exclamation point before your statement and encase your parameters in parentheses such as the following : while (!(x<=2))
A while loop has the following syntax (in logical form):
while (boolean) {run this code}
You can use the shorthand for adding myInput to your mySum:
+= will add the righthand side to the lefthand side and save that value
If you want to run the code at least once despite the value, you can use a do while loop. The logic behind it is: do {this} while (boolean);

Using delimiters to split an equation and run it

So I am doing a project for a class of mine and it involves the use of delimiters and other scanner methods. However I've been doing a lot of research and the book we have does not clearly explain as to how it works. So after several headaches and trying to understand I figured I'd ask here (EDIT: This is something somewhat similar I found [relating to delimiters and splitting number sequences] to what my teacher was asking me and thought it would be adequate to ask it here. So before I get accused of doing my homework on here I wanted to clarify)
Here's what I have typed so far:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
/* sc.useDelimiter("\\s*"); With some help and research I found
out that the \\s* actually causes every character to be split
apart. so 33 is 3 3 */
int sum = sc.nextInt();
while(sc.hasNextInt( ))
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And my last attempt got me a weird output:
----jGRASP exec: java addUp
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 8
----jGRASP: operation complete.
Now I don't know a ton and I'm sure if I came in with something more complicated than the progress of what we've been through would not be appreciated (since I know I've seen some people answer other questions that is way over my understanding). So keep it dumbed down for me if you can XD. Thanks.
The problem with your code at the moment is that your while loop is checking for while(sc.hasNextInt( )), but it's expecting an operator. Change that to while(sc.hasNext() and you should be ok.
Additionally, when facing problems like this, try running your code in a debugger and stepping through it. You'd see pretty quickly that it didn't enter into the while loop and that would help you diagnose the problem. If you don't have access to a debugger, just put in some System.out.println() statements.
UPDATE
So, I ran your code in a debugger (after changing the while loop as I described), and the first thing I noticed was that the first call to sc.nextInt() returns 3, not 33, because of the reason H L explained. Having removed the call to setDelimeter, the code runs fine. It should now look like:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
//sc.useDelimiter("\\s*"); <-- don't do this
int sum = sc.nextInt();
while(sc.hasNext( )) // <-- not hasNextInt
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And outputs:
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 1249
Again, you should have spotted this if you stepped through your code in a debugger (Eclipse, IntelliJ, NetBeans, jdb, etc).
There are multiple issues with your code:
You call the next() and nextInt() methods multiple times within the while loop which consumes too much of our input.
The sum is initialized to 0 and the very first operand is omitted.
Only the last else block is executed because you compare strings with characters (single quotes instead of double quotes) which always evaluates to false.
Code:
// WRONG: sc.useDelimiter("\\s*");
int sum = sc.nextInt(); // consume the first token, must be an integer
while (sc.hasNext()) { // as long as there are more tokes, do the following
String operator = sc.next(); // read next token, must be a + or - sign
int operand = sc.nextInt(); // read next token, must be an integer again
// depending on the arithmetic operator we update the sum variable
if (operator.equals("-")) {
sum = sum - operand;
} else if (operator.equals("+")) {
sum = sum + operand;
} else {
// if the operator variable contains something else than a + or - sign
// we throw an exception. In general this is the preferred way to avoid
// that the software changes into an undefined state.
throw new RuntimeException("Unknown operator: " + operator);
}
}
System.out.println("Sum is: " + sum);
First Problem (Apparently corrected in an edit to the quesiton)
You call sc.next() in every if statement. Call it once, and then use the value when you need it. If you keep calling it, you'll keep eating your input!
String op = sc.next();
if (op.equals('-') {}
else if (op.equals('+') {}
else {}
Second Problem
You never initialize sum to the first number. You skip the first number completely! Start off like this to make sure you consume the first int before you consume the first operator.
int sum = sc.nextInt();
Third Problem
hasNextInt() only returns true if the next token is an int. It returns false if the next token is an operator like "+" or "-". Change your while to loop on hasNext().
The last fix may cause you to consume a "/n" or some other line seperator nonsense on your last iteration of the loop. as it stands, it looks like this will only cause you to print the sum twice. That seems like something you should be able to solve on your own.
Rather than making me edit my answer four MORE times, try to do this on paper, going in circles for the while loop. Consume an int. Consume an operator. Consume an int. Consume an operator. Consume an int. If you break that order, your logic isn't in the right order. Know the logic before you even try to write code.
Go read the Javadoc for Scanner to see what each method you are calling actually does. Learn about Streams in Java so you understand how they work.

Error running or compiling this code java...Very confused program wont run

This program wont run on netBeans or compile in terminal...I dont think i have any erros in the itself..
This program needs to display the area of a circle
there cannot be any invalid input (letters, &^#,..etc)
Please and thank you for your time ;)
**import java.util.Scanner;
/**
*
* #author Omar Sugule
*/
public class AreaCircle {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in); // read the keyboard
try {
double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
System.err.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
System.out.println("This program will calculate the area of a circle");
System.out.println("Enter radius:");//Print to screen
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r);
String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle is " + area);
}
}**
You know that this won't work:
try {
double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
System.err.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
since you declare r from within the try block, it is only visible inside the try block and is completely invisible elsewhere (this is called being out of "scope").
Instead:
Declare double r before the try block and initialize it to 0.0:
double r = 0.0; // corrected as per mfrankli
Try to get the input in the try block
enclose all in a while loop and continue looping until the input is valid
don't re-declare r after the try block.
work on improving your code formatting, in particular to get your code indentation uniform. Doing this will make the code a lot easier for you and us to debug.
Work on asking better questions here. It's usually a good idea to give all the information necessary to help you in the initial question. Yours leaves out a lot of stuff making us have to guess which can lead to incorrect or confusing answers.
I've just tried out your program, and the only real problem that I see is that you have this bit at the beginning that waits for user input:
try {
double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
System.err.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
Since that code comes before the program produces any output, the effect is of a program that simply hangs; it's not obvious to the user that they should enter a number. (And indeed, they needn't bother worrying too much about the number they enter, since the program just prompts them to enter another number a bit later down:
double r = sc.nextDouble(); // Read in the double from the keyboard
and it's this second one that is actually used.)
Remove the asterisks at the beginning and end of file. The rest is okay, except having to press enter before actually giving any input.

Categories