I can't seem to understand how to use a while loop to determine whether a number is positive or not. While (I > 0), if I put any positive number, it will always result above 0 meaning there's an infinite loop.
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
while (i > 0)
{
System.out.println("The value is: " +i);
}
System.out.println("Sorry. Only positive values.");
Also, when I input a negative number, it doesn't go back to the scanner to possibly input a positive number.
You can go to this kind of approach:
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
Scanner scan = new Scanner(System.in);
while (i >= 0) {
System.out.print(" Please enter a value: ");
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
break;
}
}
System.out.println("Sorry. Only positive values.");
I believe this is what you're trying to achieve.
int i = 0; // int is 0
while (i <= 0) {
// int is 0 or a negative number
System.out.println("#1\n Input Validation\n Positive values only");
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
System.out.println("Sorry. Only positive values.");
}
// if number is positive then continue to termination. If negative then repeat loop
}
Pay closer attention to where you place your while loop as your initial placement would certainly result in an infinite loop
while (i > 0)
{
System.out.println("The value is: " +i);
// number is positive - repeat loop containing only this line of code to infinity
}
// number is either 0 or negative so continue to termination
Related
i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"
I wrote a code for school in java that verifies if a number is an armstrong number. I programmed it so that it runs as many times until the user inputs 0, at which the program will terminate. I am having 2 problems.
The code only works the first time through, if the user inputs 371 (an armstrong number) the first time, it works, but after that it returns that the number is not an armstrong number.
When the user inputs 0, it still shows the statement whether it is or is not an armstrong number, which I don't want it to.
This is the code:
import java.util.Scanner; //import Scanner for user input
public class Ch6Project {
public static void main(String[] args) {
int userNum, totalValue = 0, num, numLength; //declare variables that will be used
String suserNum; //declare user input variable
Scanner input = new Scanner(System.in); //declare a Scanner
System.out.println("Welcome to the Armstrong Number Program."); //description
System.out.println("\nTo calculate an Armstrong number: ");
System.out.println("\t 1. Cube each digit of the number.");
System.out.println("\t 2. Take the sum of these cubes.");
System.out.println("\t 3. If the sum equals the number, it is an Armstrong Number.");
System.out.println("\t e.g. 3^3 + 1^3 + 7^3 = 317");
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user input
userNum = Integer.parseInt(suserNum); //parse user input
numLength = suserNum.length(); //calculate length of user input
for (int i = numLength; i > 0; i--) { //create loop to run for n times
num = Integer.parseInt(suserNum.substring(numLength - 1, numLength)); //get last digit of number
totalValue += Math.pow(num, 3); //cube a digit
numLength--; //subtract userNum by 1 to get the rest of the digits
}
if (totalValue == userNum) { //if total value equals user input, it is Armstrong #
System.out.println("Your number is an Armstrong number.");
} else { //if total value does not equal user input, it is not an Armstrong #
System.out.println("Your number is not an Armstrong number.");
}
} while (userNum != 0); //run loop until user input == 0
input.close(); //close user input
}
}
Change your code so that it breaks immediately after entry of the userNum
e.g.
userNum = Integer.parseInt(suserNum); //parse user input
if (userNum == 0) {
break;
}
then you can also change your loop to a endless loop
while (true) {
// your code
}
It works only the first time because you don't reset your sum variable: just after the do insert:
do {
totalValue =0;..
}while (userNum != 0);
plus, your code doesn't immediatly exit because the check of the condition is at the end, hence you insert the number, the code is executed and THEN you check. BTW: when you can, avoid using break statement.
Put an if controll after the reading of the number, like this:
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user inputuserNum =
Integer.parseInt(suserNum); //parse user input
if(userNum !=0){...your code...}
}while (userNum != 0);
There are a ton of more elegant way to code it but this should do the work
public class E1 {
public static void main(String[] args) {
int c = 0, a, temp;
int m = 153;
int n = m;
temp = n;
while (n > 0) {
a = n % 10;
n = n / 10;
c = c + (a * a * a);
}
if (temp == c)
System.out.println(m + " is an armstrong number");
else
System.out.println(m + "is not an armstrong number");
}
}
Here's what my program is supposed to do:
This is a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
My code is working but right before it stops it initializes either the max or min as the -99, instead of the last intended integer in the series, then ends. What can I do to stop that?
Here's the code:
public static void main(String[] args)
{
//Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//create variables
int maxInt = -1000; //number that will be the largest initialized very low
int minInt = 1000; //number that will be the smallest initialized very high
int input = 0; //to hold the user's integer entry
//loop for the user to enter as many integers as they want
while(input != -99)
{
//General Instructions and initialization of input
System.out.println("Enter an integer. "
+ "When you are finished, please enter -99.");
input = keyboard.nextInt();
if(input > maxInt)
{
maxInt = input;
}
else if(input < minInt)
{
minInt = input;
}
}
System.out.println("Your lowest number is: " + minInt);
System.out.println("Your highest number is: " + maxInt);
keyboard.close();
}
Your input is assigned inside your while-loop thus not yet -99 when the loop starts. Therefore runs the loop with -99 and then stops at the end.
while (input != -99) {
System.out.println("Enter an integer. " + "When you are finished, please enter -99.");
input = keyboard.nextInt());
if (input == -99) {
break;
}
if (input > maxInt) {
maxInt = input;
} else if (input < minInt) {
minInt = input;
}
}
Now the loop ends when there is a input of -99 due to the break statement.
You need to check the input value before assigning the maxInt or minInt variable for -99 if it is your sentinel control value.
Example
if ( input > maxInt && input != -99 )
{
maxInt = input;
}
else if ( input < minInt && input != -99 )
{
minInt = input;
}
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
I was wondering how you can the scanner can pick up all the different numbers on the same line. my assignment has requires us to compute grade averages and he wants it to be like:
Enter the number of grades: 5
Enter 5 grades: 95.6 98.25 89.5 90.75 91.56
The average of the grades is 93.13
I think for the scanner to get those number it requires an array? but we haven't learned those. Any help would be awesome! So far I have:
// number of grades input
do {
System.out.println("Enter number of grades");
// read user input and assign it to variable
if (input.hasNextInt()) {
numGrade = input.nextInt();
// if user enters a negative grade will loop again
if (numGrade <= 0) {
System.out.println("Your number of grades needs to positive! Try again");
continue;
// if grade number > 0 set loop to false and continue
} else {
cont = false;
}
// if user does not enter a number will loop again
} else {
System.out.println("You did not enter a number! Try again");
// get the next input
input.next();
continue;
}
// only not loop when boolean is false
} while (cont);
// user input of grades
do {
// prompt user to enter the grades
System.out.println("Enter the " + numGrade + " grades");
// assign to input
if (input.hasNextDouble()) {
grades = input.nextDouble();
// check if a grade is a negative number
if (grades <= 0) {
// report error to user and loop
System.out.println("Your grades needs to positive! Try again");
continue;
// if user enter acceptable grades then break loop
} else {
cont2 = false;
}
// check if user entered a number
} else {
// if user did not enter number report error
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
// only not loop when boolean2 is false
} while (cont2);
// average calculation
average = grades / numGrade;
System.out.println(average);
}
I would suggest this
// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"}
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
//parse each value to double and adds it to total
total+=Double.parseDouble(grades[i]);
}
double average= total/grades.length;
I think in your assignment the separate spaces means that you should have each number stored in a specific location or variable.
For example:
Enter three number : 1 2 3
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
now Scanner will read by nextInt() method. if it read space then will finished saving value in that variable.
Another Example that read array elements:
Enter three number: 1 2 3
int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
myArray[i] = input.nextInt();
}
Note that the loop will run 3 times as the length of the array.
Also note in the code that input reference for Scanner class but I didn't declare it.