how to use a while loop correctly - java

Write a program that uses a while loop to perform the following steps:
Comment by labelling each part: //Part A, //Part B, etc...
A.)Prompt the user to input 2 integers: firstNum and secondNum. Use 10 and 20.
B.)Output all odd numbers between firstNum and secondNum.
C.)Output the sum of all even numbers between firstNum and secondNum.
D.)Output the numbers and their square between 1 and 10.
E.)Output the sum of the square of odd numbers between firstNum and secondNum.
F.)Output all uppercase letters.
Again I am new to while loops and I am totally lost. I have tried reading a bunch but I am better at learning if someone shows me how to do something. I am open to all suggestions. I have just completed 8 other programs using if else statements and now trying to get the hang of loops. Thanks!
This is my pathetic attempt so far LOL
import java.util.Scanner;
public class whileLoop
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Part A
int firstNum = 10;
int secondNum = 20;
System.out.println("Please enter two integers: ");
int oddNum = keyboard.nextInt();
//Part B
while(firstNum <= secondNum)
{
if(firstNum % 2 != 0)
}
oddNum = firstNum + secondNum;
firstNum++;
}
System.out.println(""+oddNum);
}
}

I would like to show you how to use while loop on
Output all odd numbers between firstNum and secondNum.
Output the sum of all even numbers between firstNum and secondNum.
Output the sum of the square of odd numbers between firstNum and secondNum.
int i=firstnumber;
int sum=0;
int sumofsqr=0;
while(i<=secondnumber){
if(i%2==0){
System.out.println(i);
sum+=i;
}
else{
sumofsqr+=i*i;
}
i++;
}
System.out.println("Sum of odd " + sum + " Sum of sqr of even " + sumofsqr);

I think you meant to do this:
//Part B
int temp = firstNum;
while(temp <= secondNum)
{
if(temp % 2 != 0)
{
System.out.println(""+temp);
}
temp++;
}

Related

For loop in prime factorization calculator displays composite numbers as well as the loop does not restart

When the for loop detects a number that is less than the positive integer inputted by the user and perfectly divisible, it prints it and that is because the for loop just continues counting through each number. However, I need it to prime factorize the positive integer inputted by the user.
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int Number = console.nextInt();
for (int counter =2; counter < Number; counter++) {
if (Number % counter == 0) {
System.out.print(" "+counter);
}
}
}
}
What you need to do to print all factors is to divide Number by counter when you've determined that counter is a factor. You also need to try counter again, in case there is more than one copy of a factor in a number, e.g. 12 is 2 * 2 * 3. Don't forget to print whatever Number is at the end, in case it didn't drop all the way to 1.
for (int counter = 2; counter <= Math.sqrt(Number); counter++) {
while (Number % counter == 0) {
Number /= counter;
System.out.print(" " + counter);
}
}
// Print what's left.
if (Number > 1) {
System.out.println(" " + Number);
}
As an aside, I've also changed the for loop condition to stop at the square root of Number, because for prime factor trials, if you've found a factor greater than the square root, then you should have found the corresponding factor that is less than the square root first.
Additionally, normal Java naming conventions would have you name the variable number in lowercase, to avoid confusion with classes such as java.lang.Number.
Your on the right track you just need to divide Number (num in the below code) by counter in the loop:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
System.out.printf("Prime factors of %d: %s%n", num, getPrimeFactors(num));
}
public static List<Integer> getPrimeFactors(int num) {
List<Integer> primeFactors = new ArrayList<>();
for (int counter = 2; counter <= num; counter++) {
while (num % counter == 0) {
primeFactors.add(counter);
num /= counter;
}
}
if (num > 1) primeFactors.add(num);
return primeFactors;
}
}
Example Usage:
Enter a positive integer: 12
Prime factors of 12: [2, 2, 3]

Write a program to calculate the sum of the factorials of the first n positive integers?

I have this question for homework: Write a program to calculate the sum of the factorials of the first n positive integers.
This is what I have done so far but I am not getting the output that I should get. Can someone tell me what have I done wrong.
System.out.print("Enter a number: ");
int num=input.nextInt();
for (int i=1; i<=num; i++) {
num=num+i;
}
System.out.print(num);
I suggest this, for example:
public static void main(String... args){
int n=10;
BigInteger j=BigInteger.valueOf(1);
BigInteger k=BigInteger.valueOf(0);
for(int i=0;i<n;i++){
j=j.multiply(BigInteger.valueOf(i+1));
k=k.add(j);
//System.out.println(j + "\t" + k);
}
System.out.println("Sum of " + n + " first factorials equals: " + k);
}
I hope it helps.
Try this:
int n, c, fact = 1;
do {
System.out.println("Please enter a positive integer.");
n = input.nextInt();
} while ( n < 1 );
for ( c = 1 ; c <= n ; c++ ) {
fact = fact*c;
}
System.out.println("Factorial of "+n+" is = "+fact);
}
The do-while loops asks the user for an input, and repeats, if the input is smaller then 1. Furthermore your line to calculate the factorial is not correct, I guess.
Note: This example does not prevent a "wrong" input like 12.5

Java loops and zero divisor

I am creating a program that will calculate two numbers. My issue is 0 will be an illegal input to the program but instead of asking again for two numbers.
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
I've done all the code and it mostly works and there is no visible error.
import java.util.*;
import java.util.Scanner.*;
public class MinilabLoopLogic
{
public static void main(String[ ] args)
{
int num1, num2, divisor, total;
Scanner kb = new Scanner(System.in); //you do it!
System.out.print("Please enter 2 integers (separated by spaces): ");
num1 = kb.nextInt();
num2 = kb.nextInt();
System.out.println("\n\nThis program will generate numbers BETWEEN "+ num1 + " " + num2);
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt();
while (divisor == 0)
{
divisor = kb.nextInt();
}
System.out.println("\n\n----------------------------------------");
//Be able to handle 1st number smaller
// OR 2nd number smalle
//Use the modulus operator to check if a number is divisible
if (num1 < num2)
{
for (total = num1+1; total < num2; total++ )
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
else
{
for (total = num1 - 1; total > num2; total--)
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
}
}//end main()
Your problem lies in your while loop looking for the divisor:
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
divisor = kb.nextInt(); // waits for more divisor input
}
You should output a string to tell the user what the problem is. say:
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
System.out.println("\nYou can't divide by 0. Try again!: ");
divisor = kb.nextInt(); // waits for more divisor input
}
Also, if you want them to have to re-enter the num1 and num2 then scanner input has to happen in that while loop.
You added the following in an edit:
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
That is because you just loop back to get another value when a zero is entered, without writing any new prompt text.
It also only gets a new divisor number, not "two different numbers". If you looped back to before "Please enter 2 integers", it'd actually end up prompting for all 3 numbers again.

How to do an addition from random numbers by the user?

I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.

Constructing a java program that reads numbers and says it's prime or lists its factors

The goal of my specific project is to write a program that will prompt the user to input two integers. The program will read the two integers and decide whether they are prime or not. if they are not the program will list the factors, otherwise it will simply print "prime" and ask the user repeatedly for two integers. Also, the program should print factors of all the numbers between the two given integers as well as the integers themselves. It will also give the average value of the prime numbers.
Goal is to make the final result look like this (assuming the two integers are 6 and 11):
Please enter two integers: 6 11
6: 2 3
7: Prime
8: 2 4
9: 3
10: 2 5
11: Prime
There are three prime numbers
The average value of the prime numbers is 9.00
Please enter two integers:
So here is my code:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int r1, r2, i, c = 0;
System.out.println("Please enter two integers : ");
int num1 = input.nextInt();
int num2 = input.nextInt();
while (num1 > 0 && num2 > 0)
{
for (i = 2; i < num1; i++) {
r1 = num1 % i;
r2 = num2 % i;
if (r1 == 0 && r2 == 0)
System.out.println("Prime");
{
System.out.println(i+ "\t");
c++;
}
}
if (c == 0)
System.out.println("Prime");
System.out.print("Please enter two integers : ");
num1 = input.nextInt();
num2 = input.nextInt();
}
}}
And this is my output when inputting 6 and 11:
Please enter two integers :
6 11
2
3
4
5
Please enter two integers :
Now i have no idea where i went wrong but i feel i must be heading somewhat in the right direction. If both inputs are prime it will print prime. If one is prime and one is not it will do what i posted above.
Any and all help is appreciated. Thank you.
Well, I'm just glancing over briefly, but your problem lies within the for loop. You start i at 2, which is sensible for checking for factors. You then check, simultaneously, if both num1 and num2 are evenly divisible by i (at this point, 2). If they are, you print "Prime". Then you iterate and do it again. Think about that carefully: how closely does it match with what you think/thought you were doing?
If I had to guess, you are missing an else line after
if (r1 == 0 && r2 == 0)
System.out.println("Prime");
{
And also the condition for the "if" should probably be negated: if (!(r1 == 0 || r2 == 0)). That should at the very least be enough to get you going in the right direction.
Good luck!
A much shorter way to do.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
public static void main(String[] args)
{
System.out.println("Please enter two integers : ");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
List<Integer> primenos = new ArrayList<Integer>();
List<Integer> result;
for(int i=num1; i<=num2; i++)
{
result = primeFactors(i);
System.out.print(i +":");
if(result.size()==1 && result.get(0)==i)
{
System.out.println(" prime");
primenos.add(i);
}
else
{
for (Integer j : result) {
System.out.print(" "+j);
}
}
System.out.println();
}
System.out.println("There are "+primenos.size()+" prime numbers");
int total = 0;
for(Integer j : primenos)
{
total+=j;
}
System.out.println("The average value of the prime numbers is "+total/primenos.size());
}
}
This is just one way of doing it.
You could find hundreds of algorithms if you google. Find one and modify to your needs.

Categories