How can I input an if statement inside a while loop? - java

import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.

If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.

The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.

The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}

To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)

You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

Related

Could anyone tell me why my program doesn't work?

The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out.
So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.
import java.util.Scanner;
public class Testing3{
public static void main(String[] args) {
int sum1 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
String number = input.nextLine();
int value =Integer.parseInt(number);
while(true) {
if (value!=0) {
number = input.nextLine();
if (Math.round(value)==value)//condition to integer{
sum1 = sum1 + value;
} else {
System.out.println(sum1);
break;
}
}
}
}
First of all, use while(true) or for(;;) to make in infinite loop
Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt.
Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.
Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:
number = input.nextInt();
if (number != 0){
sum1 = sum1 + number; //or use sum1 += number
} else {
System.out.println(sum1);
break;
}
I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.
Let's say we have a double variable called x and this evaluates to true if x is an integer:
Math.round(x) == x
I don't know whether there is a better way to do it but that's how I would do it and I like it.

How to add multiple values with while statement?

I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.

Checking for negative values with scanner in

I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p

Java, Infinite loop- multiples of 2 only

I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}

Finding the Average from a list of numbers in Java

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.

Categories

Resources