Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to write a portion of a program that calculates factorials using loops. I don't have any error messages, but I'm not getting any output.
Are there suggestions for my approach or is there a better approach using loops? Thanks!
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
while (number >= 1);
}
while (number <= 0);{
System.out.println("That's not a positive integer!");
}
System.out.print(factTotal);
}
}
This is the way I would approach the factorial portion of your problem. I would do away with the do/while loops because it appears that you are getting stuck in an infinite loop if you aren't getting output.
//Call this method when you want to calculate the factorial
public int factorial(int num){
for(int i = num-1; i > 1; i--){
num *= i;
}
return num;
}
This is what it would look like in your code.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
if(number > 0){
factTotal = factorial(number);
System.out.print(factTotal);
}
else
System.out.println("This is a negative number");
}
#Pernicious, Please see your program with slight modifications and my comments added. I think this is what you were trying to do.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
// The input number check should be before factorial calculation
if(number <= 0){
System.out.println("That's not a positive integer!");
System.exit(0);
}
//Execute factorial
do {
factTotal = factTotal * number;
number--;
// while (number >= 1); This while should be after do{}, not within do{}
} while (number >= 1);
// This check should be done immeduately after user input, not after calculation of factorial.
// while (number <= 0);
// {
// System.out.println("That's not a positive integer!");
// }
System.out.println(factTotal);
}
}
In your code, in the do...while loop, you have used this while statement:
while (number >= 1);
Did you not notice the semicolon? And what is the point of this loop? Currently it is leading to an infinite loop as the value of number never changes and thus you are getting no output. Also, your second while loop should much rather be an if statement as shown below
That piece of code is equivalent to:
while (number >= 1)
{
//doNothing
}
I believe you meant to do:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
}
while (number <= 1);
if(number < 0)
{
System.out.println("That is not a positive integer");
}
else
System.out.print(factTotal);
}
Related
I would love to know how to make it run until user enters 0, i tried doing while (i <=number) && (number != 0) but it didnot work.
import java.util.Scanner;
public class Factorial {
private static Scanner sc;
public static void main(String args[]){
int i =1, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
sc = new Scanner(System.in);
number = sc.nextInt();
while (i <=number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: "+factorial);
}
}
Initialize number to a non-zero integer and enclose everything in a while loop.
public class Main {
private static Scanner sc;
public static void main(String args[]){
int number = 7; // can just use a random starting number which is not 0
while (number != 0) { // Add a while loop to make it keep asking for factorials until 0 is given to quit
int i = 1, factorial = 1;
System.out.println("Enter the number to which you need to find the factorial or enter 0 to quit:");
sc = new Scanner(System.in);
number = sc.nextInt();
while (i <= number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: " + factorial);
}
System.out.println("Thanks for using the factorial calculator. ");
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to count a range of number with a for loop using input from scanner.
Tried writing the code but still no results
package com.example.myapplication;
import java.util.Scanner;
public class dsd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int firstnum = sc.nextInt();
System.out.println("Enter first number:");
int secondnum = sc.nextInt();
System.out.print("counting ");
for (int i = firstnum; i >= secondnum; i++) ;
{
System.out.print(i);
}
}
Upper limit :5
Lower Limit :2
Expected to see COunting 2 ,3 ,4, 5
I think it would be better to use a camel case to match the coding convention. And if you put a semicolon after the for loop, the following code will not be executed. Of course, the conditional statements in the for loop seem a little wrong.
For the example given in the question, see the code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Upper limit:");
int firstNum = sc.nextInt();
System.out.print("Lower Limit:");
int secondNum = sc.nextInt();
System.out.print("counting ");
for (int i = secondNum; i <= firstNum; i++) {
System.out.print(i);
}
}
Result (in the terminal)
Upper limit:5
Lower Limit:2
counting 2345
I have seen this mistake many times:
for (int i = firstnum; i >= secondnum; i++) ;
Please remove the ;
Is the first number always greater than the second?
If so, you should write it as the code below.
// Delete semicolon. and less then change
for (int i = firstnum; i <= secondnum; i++) {
System.out.print(i);
}
In your code you have used the "sc" scanner for both firstnum/secondnum variable. The loop of your code will print only the last number inserted.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
int start, end;
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
/*
* The block try-catch highlights the fact that you cannot insert min
* number bigger than the max number
*/
try {
System.out.print("Enter first number:");
start = sc.nextInt();
System.out.print("\nEnter second number: ");
end = sc1.nextInt();
if(start > end) throw new Exception();
i = start;
while (i<=end){
System.out.println("count: " + i);
i++;
}
}catch(Exception e){
System.out.println("You cannot start with number bigger than 'end-number' ");
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a code that will get the sum of all the digits of the input,
sample input: 241 sample output: 7
But there are restrictions in in making the program, only the basic operations, functions should be used and no string function is to be used in getting the said sum of the digits only (loop, /, %, *,-,+)are allowed to be used.
The program I am thinking should start with this..
public class SumOfDigits{
public static void main(String args[]) throws Exception{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
while(){
}
}
}
One option would be to use a modulus trick to isolate, and then sum, each digit in the input number:
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
Follow the link below for a working demo.
Demo
modulu 10 of the number will give you the last digit, the dividing it by 10 will give you the other digits, due to integer division. You can loop until you've handled all the digits:
int sum = 0;
while (num != 0) {
sum += (num % 10);
num /= 10;
}
you can use a recursive function like this
import java.util.Scanner;
public class Main {
Scanner scanner ;
int result = 0;
public static void main(String[] args) {
// initialize new instance of current class
Main thisIns = new Main();
// initialize scanner instance for this instance
thisIns.scanner = new Scanner(System.in);
//calling for getting user inputs
int i = thisIns.getUserInput();
//get the sum of the integer
thisIns.getSumOfInterger(i, 0);
System.out.println("result is " + thisIns.result);
}
public int getUserInput(){
System.out.println("Please enter an integer : ");
int i = scanner.nextInt();
return i;
}
public void getSumOfInterger(int i, int moduler) {
if (i != 0) {
moduler += i%10;
getSumOfInterger(i/10, moduler);
// return 0;
}else{
result = moduler;
}
}
}
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'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}
Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}
Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}
For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you