How to check if number is divisible by a certain number? - java

I am using AndEngine to add sprites to the screen and come across using the movemodifier method.
I have two integers
MaxDuration and MinDuration;
What i want to do is when the user gets to a score of a certain increment.
Like for example.. when the user gets to 20(the integer changes) when the user gets to 40(the integer changes). So basically count by 20 and every time the score meets a number divisible by 20 the integer's change. I hope this makes sense.
Is there any method or way to do this? I have an UpdateTime handler that can check the score just about every second.
Any ideas?

n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;

package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}

Related

While loop will not continue to ask the user for an input

I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4

Why doesn't the scanner class recognize the other numbers?

public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.

Which part of my program is in the wrong loop? JAVA

The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)

How to print prime numbers up to the user's entered integer?

Good afternoon everyone,
I'm currently trying to create a program that does the following:
Develop a code that will print all prime numbers up to the user's entered
number. An example of the output:
Enter an integer (2 or above): 19
The prime numbers up to you integer are:
2
3
5
7
11
13
17
19
Unfortunately, there is also a list of "requirements" that need to be met as well:
If the user enters a number below 2, your program should print a message that the number is not valid, and then stop.
A number is a prime number if it is not divisible by any number except 1 and itself.
For this program, in order to test a number to see if it is prime, you should try to divide the number by every value from 2 up to the number-1, to see if it divides evenly or not. For example:
--To see if 5 is a prime number:
5 does not divide evenly by 2
5 does not divide evenly by 3
5 does not divide evenly by 4
therefore 5 is a prime number
--To see if 9 is a prime number:
9 does not divide evenly by 2
9 divides evenly by 3
therefore 9 is not a prime number
This program requires you to write nested loops (that is, a loop inside a loop). One loop will be used to count from 2 up to the user's number so that you can test each of these numbers to see it it is prime. For each of these numbers, x:
A nested loop will check all values from 2 up to x-1 to see if x divides evenly by any of them.
You will need to use a Boolean variable (also referred to as a flag variable) to help you determine whether or not to print a number to the screen
The question above is in regards to my code so far below:
import java.util.*;
public class Something3 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
//Variable declaration.
int limit, number;
//get input till which prime number to be printed
System.out.print("Enter an integer (2 or above): ");
limit = kbd.nextInt();
kbd.close();
//Will print prime numbers till the limit (user entered integer).
number = 2;
if (limit >=2) {
System.out.println("The prim numbers up to your interger are: " + limit+"\n");
for(int i = 0; i <= limit;){
//print prime numbers only
if(isPrime(number)){
System.out.println(number +"\n");
i++;
}
number = number + 1;
}
}
else
System.out.println("Number is not vaild");
}
//Prime number is not divisible by any number other than 1 and itself
//return true if number is prime.
public static boolean isPrime(int number){
for(int i=2; i==number; i++){
if(number%i == 0){
return false; //Number is divisible, thus not prime.
}
}
return true;//The number is prime.
}
}
Is the limit variable I'm using the issue? Any help would be much appreciated.
your isPrime() method is returning wrong result. for loop condition is wrong i==number it should be i < number
public static boolean isPrime(int number){
for(int i=2; i*i <= number; i++){
if( number % i == 0){
return false; // Number is divisible, thus not prime.
}
}
return true; //The number is prime.
}
To check a number prime or not you don't have to check divisbility from 2 to N, all you need to check upto sqrt(N).
To find prime numbers in a range(N) use Sieve of Eratosthenes
Your actual problem was number variable. Here's your solution. There's no need of variable number. Below is your solution
import java.util.*;
public class Something3 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
// Variable declaration.
int limit;
// get input till which prime number to be printed
System.out.print("Enter an integer (2 or above): ");
limit = kbd.nextInt();
kbd.close();
if (limit >= 2) {
System.out.println("The prim numbers up to your interger are: "
+ limit + "\n");
for (int i = 1; i <= limit; i++) {
// print prime numbers only
if (isPrime(i)) {
System.out.println(i);
}
}
} else
System.out.println("Number is not vaild");
}
// Prime number is not divisible by any number other than 1 and itself
// return true if number is prime.
public static boolean isPrime(int n) {
if (n % 2 == 0)
// The only even prime is 2.
return (n == 2);
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
}
import java.util.Scanner;
class prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the value of n");
int n=sc.nextInt();
for(int i=2;i<=n;i++)
{
int count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
System.out.println(i+" ");
}
}
}
}

Better way of calculating sum of even ints

I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!
Here's what I did:
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
int divnum = number / 2;
int divnum2 = divnum + 1;
int sumofeven = divnum * divnum2;
if(number >= 2)
System.out.println("The sum of the even integers between the number is "+
sumofeven);
else
System.out.println("Invalid number entered.");
}
}
Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.
// Check the input.
if (number >= 2)
System.out.println(sum(number));
}
// Will find the sum if the number is greater than 2.
int sum(int n) {
return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}
Hope this helps. Oh, by the way, the method sum adds the numbers recursively.
Sorry, but I had to edit the answer a bit. There might still be room for improvement.
Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.
Edit: just saw the answer above me. He is right. I gave the function I suppose.
Why use a loop at all? You are computing the sum of:
2 + 4 + ... n, where n is a positive even number.
This is a very simple arithmetic progression.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
if (number >= 2) {
int sumofeven = 0;
for (int i = 2; i <= number; i += 2) {
sumofeven += i;
}
System.out.println("The sum of the even integers between the number is " + sumofeven);
} else {
System.out.println("Invalid number entered.");
}
}

Categories

Resources