Numbers to stop at the user's input - java

How do I make my program to stop at the user's input?
Here is my code:
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
if (i < x)
System.out.print(printFib(i) + " ");
else if (i > x)
break;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
So, if I enter 10 my program should stop before the number. Example:
Input: 10
Output: 0 1 1 2 3 5 8
But instead I get 0 1 1 2 3 5 8 13 21 34
How can I fix it?
int x = input.nextInt();
int fib = 0;
while (fib < x){
System.out.print(printFib(fib)+ " ");
fib++;
}
}

Don't use a for loop which right now you're using to print out Fibonacci numbers until the number of items printed is less than the entered number. Instead use a while loop that stops when the Fibonacci number itself is greater than the entered number.
Since this is likely homework, I'm just going to give this suggestion and not a code solution, but please give a solution a try, and if still stuck, come back with questions.
Pseudocode
Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
display current fibonacci number
calculate next fibonacci number and place in variable
end while loop

public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
int i = 0;
while ( printFib(i) <= x ) {
System.out.print(printFib(i) + " ");
i ++ ;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
While the number return from the printFib() method is less than and equal to the user input, it then runs the method. I've tried the code and it works.

Related

Showing largest divisible number instead of all numbers

I've started to learn basics of Java and currently I have to find and print largest divisible number.
For example number 30 can be divided by 2, 3, 6 and 10 so on the console I should show only 10. Another example is number 12 which can be divided by 2, 3 and 6 - should show 6.
I'm stuck at the point where I show the largest number. What I have so far is this one
double isItDivisible = Double.parseDouble(scanner.nextLine());
int num = 2;
if ( isItDivisible % 2 == 0 ) {
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 3 == 0 ) {
num = 3;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 6 == 0 ) {
num = 6;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 10 == 0 ) {
num = 10;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 7 == 0 ) {
System.out.println("The number is divisible by " + 7);
}
The snipped display the first occurrence instead of the largest.
You can tell how new I'm based on the snipped so please bear with me.
When you want to find the highest divisible number that is not the input you could do the following:
int highest = 1; //1 should always apply - at least for integers
//iterate from highest to lowest number
for( int d = input-1; d > 1; d-- ) {
//stop at the first number that divides the input without a rest
if( input % d == 0 ) {
highest = d;
break;
}
}
If you want to check specific numbers only, you could modify that to use a sorted collection of numbers.
//TreeSet is sorted and the reserved comparator makes it sort from high to low
SortedSet<Integer> divisors = new TreeSet<>(Comparator.reversed());
//if the collection itself is sorted the order of additions doesn't matter
//if you're using a list and don't sort it after adding elements then order of insertion is relevant though
divisors.add(2);
divisors.add(10);
divisors.add(3);
divisors.add(7);
divisors.add(6);
Integer highest = null;
//iterates in sorted order
for( Integer d : divisors ) {
if( input % d == 0 ) {
highest = d;
break;
}
}
Try this :
public static void main(String[] args)
{
// Scanner Class
Scanner scanner = new Scanner(System.in);
double isItDivisible = Double.parseDouble(scanner.nextLine());
int high = 0;
for (int i = 0; i < isItDivisible; i++) {
if (isItDivisible % i == 0) {
high = i;
}
}
System.out.println(high);
}
Edit : With divide by pecific numbers 2,3,6,7,10:
public static void main(String[] args)
{
// Scanner Class
Scanner scanner = new Scanner(System.in);
double isItDivisible = Double.parseDouble(scanner.nextLine());
int high = 0;
int[] divide = {2,3,6,7,10};
Arrays.sort(divide);
for (int i : divide) {
if (isItDivisible % i == 0) {
high = i;
}
}
System.out.println(high);
}

How to print single number only once using nested loops in Java?

Everything runs fine in my Java code except at the very end of the code. So basically I can't figure out how to print out the User's Number if it is the same. For example I am prompt the User for a starting number and an ending number (integers). So say the user enters in the same integer "10" for starting number and "10" for ending number. I want the output to only be "10" to be printed only just once. I've tried everything I can think of with trying While Loop, Do-While Loop, and For Loops but I just can't figure it out?
------------------------JAVA CODE BELOW-------------------------------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------OUT PUT BELOW -----------------------------------------------------
Now I'll print whatever numbers you'd like!
Give me a starting number:
10
Give me an ending number:
10
I counted your range of numbers:
10
11
10
----jGRASP: operation complete.
You could restructure your code as follows:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
You can use for loop:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
So you are either counting up, down or there's just one.
So
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
Or put a break in the middle of a for loop. Also there's +=, and a few things we can make more conventional.
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
The issue is in your first two while loops where you are using ">=" and "<=". You can remove "=" from the condition.
However you can improve your code as suggested in other comments.

Print odd numbers in a descending order

The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}

How does this prime number test in Java work?

The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}

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