Java program to check if a number is divisible by 5
Introduction
This program is a simple Java program that checks whether the number entered by the user is divisible by 5. The program prompts the user for a number, uses the Scanner class to read the input, and then uses the modulo operator % to check whether the number is divisible by 5. If the remainder of the division is 0, then the number is divisible by 5, and the program prints a message to the console indicating this. If the remainder is not 0, the number is not divisible by 5, and the program also prints a message to the console to indicate this.
The program uses basic Java concepts such as variables, user input, conditional statements, and console output. It also demonstrates how to use the Scanner class to read user input from the console.
Commonly used primitive data types
When writing programs that involve user input, it is helpful to have a basic understanding of the range of values that different data types can store. Here is a quick overview of some commonly used primitive data types in Java and the range of values they can store -
type of data | size | Range of storing integers |
---|---|---|
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
It is important to note that the above ranges apply to the primitive data type itself and do not take into account any constraints or limitations that may be imposed by the context or the program itself. For example, a program might restrict inputs to a specific range of values or impose additional constraints on data types.
formula
number % 5 == 0
Example 1
method
First, we import the Scanner class to read user input.
Then we create a Scanner object to read input from the console.
We prompt the user to enter a number.
We use the nextInt() method of the Scanner class to read the number entered by the user and store it in the integer variable number.
We then use the modulo operator % to check if the number is divisible by 5. A number is divisible by 5 if the remainder when divided by 5 is 0. If the remainder is not 0, then the number is not divisible by 5.
We then print a message to the console indicating whether the number is divisible by 5.
Finally, we close the Scanner object to release all resources associated with it.
This is a Java program to check if a number is divisible by 5.
import java.util.Scanner; public class DivisibleBy5 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (number % 5 == 0) { System.out.println(number + " is divisible by 5."); } else { System.out.println(number + " is not divisible by 5."); } scanner.close(); } }
illustrate
In this program, we first import the Scanner class to read user input. We then prompt the user to enter a number and read it using the nextInt() method of the Scanner class.
Then we use the modulo operator % to check if the number is divisible by 5. A number is divisible by 5 if the remainder when divided by 5 is 0. If the remainder is not 0, then the number is not divisible by 5.
We then print a message to the console indicating whether the number is divisible by 5. Finally, we close the Scanner object to release all resources associated with it.
Output
Enter a number: 55 55 is divisible by 5.
Example 2
method
Create a Scanner object to read input from the console.
Prompts the user to enter a number.
Use the Scanner object's nextBigInteger() method to read the input and store it in a BigInteger variable.
Use the mod() method of the BigInteger class to calculate the remainder of the input number divided by 5.
Compare the result of mod() with BigInteger.ZERO and check whether the remainder is equal to 0.
If the remainder is 0, print a message to the console indicating that the number is divisible by 5.
If the remainder is not 0, print a message to the console indicating that the number is not divisible by 5.
Close the Scanner object to release all resources associated with it.
Here is a Java program for checking whether a number is divisible by 5, assuming the input number is not very large -
import java.math.BigInteger; import java.util.Scanner; public class DivisibleBy5 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); BigInteger number = scanner.nextBigInteger(); if (number.mod(BigInteger.valueOf(5)).equals(BigInteger.ZERO)) { System.out.println(number + " is divisible by 5."); } else { System.out.println(number + " is not divisible by 5."); } scanner.close(); } }
illustrate
In this program, we use the BigInteger class in the java.math package to handle large integers. The program prompts the user to enter a number, uses the Scanner class to read the input, and then creates a BigInteger object to store the entered number.
To check whether a number is divisible by 5, we use the mod() method of the BigInteger class to calculate the remainder of the input number divided by 5. We compare the result of mod() with BigInteger.ZERO to check if the remainder is equal to 0. If the remainder is 0, then the number is divisible by 5, and the program prints a message to the console to indicate this. If the remainder is not 0, the number is not divisible by 5, and the program also prints a message to the console to indicate this.
Please note that we use BigInteger.valueOf(5) to create a BigInteger object representing the value 5 because the % operator cannot be used directly with BigInteger objects.
Output
Enter a number: 56 56 is not divisible by 5.
in conclusion
We explored two different ways to check if a number is divisible by 5 in Java.
The first method uses a simple modulo operation to calculate the remainder of the input number divided by 5, while the second method uses the BigInteger class to handle large integers and uses the mod() method to perform the same operation.
The above is the detailed content of Java program to check if a number is divisible by 5. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools
