Hey everyone so I've been trying to write what should be a really easy counting program for my CS class, but for some reason it keeps spitting back out the "Please enter a number (0 to stop): " prompt and seems to completely disregard the while loop. If the condition inside the while loop is being met, why does the while loop not stop even if 0 is entered? I have done C# in the past, but I'm not really familiar with Java's caveats, so if there's anything weird that Java doesn't like me to do let me know. For a more detailed description of the program, it's supposed to read both negative and positive numbers from the user, output the sum of the negatives and the positives individually, and then take the average. (Obviously below is just the problematic piece of code.)
Scanner scanner = new Scanner(System.in);
double average;
double numPositive=0.0;
double numNegative=0.0;
double input = 0.0;
do
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += scanner.nextDouble();
}
else if (input > 0.0)
{
numPositive += scanner.nextDouble();
}
} while (Math.abs(input) > 1.0e-6); // make the tolerance whatever you want.
You never change input after the initial assignment; the loop will continue on forever. I think you forgot to call scanner.nextDouble() again.
You're not taking in input after initially retrieving it.
Your scanner.nextDouble() assigns to numNegative and numPositive- neither of which is checked by the while loop.
while (input != 0.0)
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += input;
}
else if (input > 0.0)
{
numPositive += input;
}
}
You are not assigning a value to input anywhere inside your loop. So, the initial value remains, and the loop won't exit.
Related
while (input != '1'){
String customer;
customer = JOptionPane.showInputDialog("Enter customer's name: ");
String type;
type = JOptionPane.showInputDialog("Choose type of photocopy: G/C");
if (type.equals("G")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.10;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.05;
}
} else if (type.equals("C")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.20;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.10;
}
}
JOptionPane.showMessageDialog(null, "Customer name : "+customer+"\nType of Photocopy : "+type+"\nNumber of Photocopy : "+noOfPhotocopy+"\nTotal Price : RM"+ (float)totalprice);
String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");
Please help me with this code. I cannot determine what is wrong with this code. When I run this program, it seems that the looping is not working. This is my assignment project and need to be submit earlier.
Why is my loop not looping?
You break unconditionally. break will always exit the enclosing loop.
Also you have a type confusion in your loop condition between char and int. It is legal due to type coercion (int will be converted to char for comparison or vice versa), but it won't do what you intend.
'1'
is a char. It's a UTF-16 character whose int value is 49.
1
is an int
You really want this:
while (input != 1) {
Here's another way to approach this that you can apply generally when programs go pear-shaped (don't work as expected).
Make a backup of this code and start a new Java class. In that class create a smaller example. Maybe something like this:
while (input != '1') {
String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");
This program has the same bugs, but is much smaller. Can you see the problem in that smaller program?
This approach done either by removing code or commenting it out allows you to isolate a bug by trial and error. Over time you'll develop an intuition for the bugs and see them immediately, but this approach goves you an avenue for getting to that point.
while (input !='1'){
is wrong. Because input is int. Inside your code you write:
input = Integer.parseInt(input1); // so input is int type
Rewrite it as:
while (input != 1){
int input=1;
Scanner scn=new Scanner(System.in);
System.out.println("Start!!!");
while (input!=0) {
System.out.println("Enter 0 to exit!!");
input=scn.nextInt();
}
System.out.println("Finish!!!");
Refer this code for your code.
No need to use break inside loop. You can use it with conditional break.
Hello I'm trying to write a program that prints 3 numbers from a range being restricted to numbers from 0 to 99,but my If statement isn't double checking the variable.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0);
System.out.println("Outside range program terminated.");
Two problems that I see:
Your second input (within the first IF) is not checked with the code shown.
The else statement will NOT check the above mentioned problem because you've already passed that decision point when the original IF executed. The else is dependent on the IF's result. Here would be one way to fix.
Finally the 'else' needs brackets { }.
int input1 = 0;
Boolean myLoop = true; //Sets up our loop flag
while(myLoop){ //Loop while true
System.out.println("Please enter an integer between 0-99");
input1 = Input.nextInt();
if (input1>99||input1<0){ //If input is outside the range send msg.
System.out.println("Data range error");
}else{ //If input is in range, end loop.
myLoop=false;
}
}
This will continue to check until it get valid values.
While the others have given you a good code sample, I will like to point out where your code issue is. The code is not doing the double checking here because you have placed a semi-colon right at the end of the second if-else check, and the program will do nothing when it fulfill the if condition.I have replaced it with curly bracket. Try to compile and run it again.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0){
System.out.println("Outside range program terminated.");
}
I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create an input that will Verify the input is an Integer, and that it is positive. Right now i have this. How should i check if the integer is positive
EDIT: Also i need it to keep asking until you enter a positive integer
/**
* pre: none
* post: returns a positive integer as entered by the user
*/
public static int getInput(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
while (!scan.hasNextInt()){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
scan.next();
}
a = scan.nextInt(); //Assigns entered integer to a
return a; //replace with correct code
}
You can do this in a single loop, similar to the one that you have for skipping invalid input. However, since the loop needs to ensure two things (i.e. a number is entered, and that number is positive) you need to modify its body.
Since the input needs to be done at least once, a do/while loop is a better choice.
Start with a loop that satisfies the condition that you want, i.e. "I got a number, and that number is positive":
int num = -1;
do {
// We'll provide content of this in a moment
} while (num <= 0);
Once the loop exits, you know that num > 0, so the only task now is to write a body of the loop that takes us closer to that goal.
Inside the loop we need to check that the user entered a number. If he did, we harvest that number; otherwise, we tell the user to try again:
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scan.nextLine();
}
That's it - now you have a loop body that reads the value for you, and a loop condition that ensures that the value is positive on exit. Combine the loop with the loop body, and try it out. It should do the trick.
Simple:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
On a side note:
Check Math.signum()
Returns the signum function of the argument; zero if the argument is
zero, 1.0 if the argument is greater than zero, -1.0 if the argument
is less than zero.
You can try this:
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}
This is my first attempt at java problem I have been given as part of my Programming assignment.
I must make a program which calculates the average of a list of numbers that a user enters. the data enty should be terminated when 0 is entered. my problem is with this "ALL NEGATIVE NUMBERS SHOULD BE IGNORED"
for some reason the following code does not work, when I enter a negative number it should be ignored but for some reason it terminates the data enty
import java.util.*;
class Task_8
{
public static void main()
{
Scanner inputLine = new Scanner(System.in);
float row, numberentered, numbersum = 0, negativenumber = 0;
double result, count = 0;
System.out.println ("Welcome to Task 8 of 10 of my Programming Assignment... Nearly There!");
System.out.println ("_____________________________________________________________________");
System.out.println ();
System.out.println ("Enter as many numbers as you like and this program will tell you the arithmatic mean");
System.out.println ("Terminate data entry by entering 0");
do{
System.out.print ("Please enter a number: ");
numberentered = inputLine.nextInt();
count++;
if (numberentered < 0)
{
numberentered = negativenumber;
}
numbersum = ( numberentered + numbersum ) - negativenumber;
}
while ( numberentered !=0 );
result = numbersum/count;
System.out.println ();
System.out.println ("*************************************");
System.out.println ();
System.out.println ("The sum of all of the numbers you entered is " +numbersum);
System.out.println ("You entered " + count + " numbers");
System.out.println ("The Average/mean of the numbers that you entered is " + result);
System.out.println ();
System.out.println ("*************************************");
}
}
any Ideas guys?
Thank you
The variable negativenumber always has the value zero. When you set numberentered to negativenumber the "while" condition is met, and the loop exits. A better strategy would be to us "continue" to skip the rest of the loop body when a negative number was entered.
If you want to ignore the negative number, then don't include it in your calculation. Instead do something like:
if (numberentered > 0)
{
numbersum += numberentered;
}
Examine the following block of code:
if (numberentered < 0)
{
numberentered = negativenumber;
}
What this is doing is setting numberentered to 0. Then, at the end of your do-while loop, you have this:
while(numberentered != 0);
So, whenever the user types in a negative number, you set numberentered to zero. When you reach the end of the loop, numberentered != 0 is false, so the loop exits.
The simpler solution, and something more akin to what you will learn to do on a regular basis in the future, is to simply check the value of the number in an if statement and then add it or not based on its value.
if(numberentered > 0)
numbersum += numberentered;
This is clean, concise, and removes the need for the negativenumber variable which is superfluous and could be confusing. If you were looking at this code a year from now, would you remember what negativenumber meant, or why it was set to zero? Write your code as if somebody else will have to read it and understand it. Your professors will, and, in the future, your colleagues will.
On another note, you are reading in integers (with inputLine.nextInt()) but storing them in a float. You've also declared count as a double. You most likely will want to declare count, numberentered, and numbersum as an int.
You never assign a value other than 0 (in initialization) to negativenumber, then you do
if (numberentered < 0)
{
numberentered = negativenumber;
}
and the do...while-loop terminates because numberentered is 0.