how to determine the multiples of numbers in java - java

read 2 numbers and determine whether the first one is a multiple of second one.

if (first % second == 0) { ... }

Given that this is almost certainly a homework question...
The first thing you need to think about is how you would do this if you didn't have a computer in front of you. If I asked you "is 8 a multiple of 2", how would you go about solving it? Would that same solution work if I asked you "is 4882730048987" a multiple of 3"?
If you've figured out the math which would allow you to get an answer with just a pen and paper (or even a pocket calculator), then the next step is to figure out how to turn that into code.
Such a program would look a bit like this:
Start
Read in the first number and store it
Read in the second number and store it
Implement the solution you identified in paragraph two using the mathematical operations, and store the result
Print the result to the user.

//To check if num1 is a multiple of num2
import java.util.Scanner;
public class multiples {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number!");
int num1 = reader.nextInt();
reader.nextLine();
System.out.println("Enter another number!");
int num2 = reader.nextInt();
if ((num1 % num2) == 0) {
System.out.println("Yes! " + num1 + " is a multiple of " + num2 + "!");
} else {
System.out.println("No! " + num1 + " is not a multiple of " + num2 + "!");
}
reader.close();
}
}

A number x is a multiple of y if and only if the reminder after dividing x with y is 0.
In Java the modulus operator(%) is used to get the reminder after the division. So x % y gives the reminder when x is divided by y.

Related

I'm new to Java. I coded a Java program that adds two numbers. Can't get to display the sum as int.

Hi I'm totally new to the Java language and my professor gave us an assignment that's not too complicated. I've done most of it correctly. Here's what we're supposed to do. If you enter two integers the sum should be an int. If you enter two doubles the sum should be a double. And if either of the two is a double then also the sum should be a double. And if either of the two can be interepreted as a Binary number, it should be treated as such. Lastly, if both numbers are Binary then the sum should be displayed in binary. The code I have so far, does everything except when I enter two ints it gives me the sum as a double, can somebody please suggest where I should make a change to fix that?
This is my code so far:
import java.util.Scanner;
public class ProjectZero
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
cin.useRadix(2);
System.out.print("Enter two numbers separated by a space: ");
if (cin.hasNextInt())
{
int first = cin.nextInt();
if (cin.hasNextInt())
{
int second = cin.nextInt();
bigFunction(first, second);
}
else if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else if (cin.hasNextDouble())
{
double first = cin.nextDouble();
if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else
System.out.println("Please try again and enter numbers.");
cin.close();
}
public static void bigFunction(int a, int b)
{
int sum = a + b;
System.out.print("The sum of " + Integer.toBinaryString(a) + " (Decimal value: " + a + ")");
System.out.println(" and " + Integer.toBinaryString(b) + " (Decimal value: " + b + ")" + " is " + Integer.toBinaryString(sum));
}
public static void bigFunction(double a, double b)
{
double sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum);
}
}
even easier answer do
instead of if .hasNextDouble
if (first % 1 ==0)
{
//you have an integer
}
else
{
//it is not an integer
}
the % means modulus which basically divides something and check if there is a remainder if there is a remainder after deviding a number by 1 it is not an int
The easiest way is to read the two inputs as Strings. Then check the strings to see whether they contain only the digits 0 and 1 (if so, binary number). If not binary, check whether it can be interpreted as a double. If so, cast to int and see if it is the same value (then it is an int). If it can't be read as a double, it is bad format. Note that you might have to consider if the number is too big to fit an int, or long, etc.
The reason why you are getting the sum as double when both the input's are int is because you are changing the default radix of scanner, hence it fails to recognize the input as int and instead reads it as a double.
If you don't change the radix of scanner, it will use the default radix (10) and scan input at base 10. Now this will work for input: int & double; but will not work for binary input's. All this boils down to your choice of implementation and I don't think you can accomodate all the required inputs with your current approach. I'd suggest following #FredK approach and take the input as string (even that approach has it's own flaws).
There is no way for you to check if the two numbers entered are in fact two separate ints. And also, you are asking for two double parameters and your sum is also a double so when you put the ints into the bigFunction, you are always casting them to doubles and the sum is a double so you will always get a double.
You need to have a check inside the bigFunction function to check if they are in fact two doubles or two ints, etc.
Or in fact make separate functions, but always strive for laziness!
Hope that gets the gears churning!
In java an integer is a form of double if you run the code
int a =4
int b =5
double b = a +c
System.out.print(b);
this would work as an integer is a form of double.
the easiest way would be to rename your double method to something else
best solution
userinput (the double) = variable
if ((variable == Math.floor(variable))
this rounds the number do so 5.9 would be 5 and if the that is equal to variable you have an int.

Infinite multiplication questions

I am trying to make a program that randomly generates two single digit numbers, creates a multiplication question, asks the user for the answer, counts the amount of questions and correct answers, and after every question the user is able to stop the loop to see how many he got correct out of the number of questions that were given.
I believe that I should be using a while loop (probably the easiest way) but I don't know exactly how to go about doing that. Here is what I currently have:
int number = 0;
int number1 = (int)(Math.random() * 10); //Produce two single digit numbers
int number2 = (int)(Math.random() * 10);
Scanner input = new Scanner(System.in); //Create Scanner
System.out.print("What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
while (number <= 10) {
if (number1 + number2 != answer ) {
System.out.println(" Incorrect!\n Would you like to see your overall result? (yes or no)");
}
else {
System.out.println(" Correct, great job!\n Would you like to see your overall result? (yes or no)");
}
}
Since this seems like an assignment I'll just give you pseudocode
MainMethod
{
//Create a new Random to generate random numbers
//(Import java.util.random)
//You need variables for:
//Total number of questions asked
//Total number of correct answers
//Start the question loop
while(true){
//Generate your two random numbers
//Ask the question
//Index the total number of questions
//Get their answer
//Check their answer
if(answer is correct){
//Index correct answers
}
//Ask whether they want to continue
//Check whether they want to stop
if(they want to quit){
//Break out of the while loop (break;)
}
}
//Tell them how many they got correct out of the total
}
Maybe I gave a little too much, but I hope this helps.

Really confused on where to begin, multiple choice operations?

I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."
An example output I'm given is:
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.
You generally first want to start reading input from STDIN:
Scanner in = new Scanner(System.in);
Then, I would read all parameters and afterwards perform the computation:
System.out.print("Enter the first number: ");
int left = Integer.parseInt(in.nextLine());
System.out.print("Enter the operation: ");
String operation = in.nextLine();
System.out.print("Enter the second number: ");
int right = Integer.parseInt(in.nextLine());
Now that all input is collected, you can start acting.
int result;
switch(operation)
{
case "+": result = left + right; break;
case "-": result = left - right; break;
case "*": result = left * right; break;
case "/": result = left / right; break;
case "%": result = left % right; break;
default: throw new IllegalArgumentException("unsupported operation " + operation);
}
System.out.println(left + " " + operation + " " + right + " = " + result);
Sounds like we are doing your homework! :) Make sure you learn these things or else it will eventually bite you. You can only delay the inevitable. With that "fatherly advice", here ya go.
First, you need to be able to read input from the console so that you can get the input numbers and operation. Of course, there are whole answers on this already. One link:
Java: How to get input from System.console()
Once you have the input, then you can work with it.
You will need to look at the items entered. They say you don't need to validate the numbers but you need to validate the operation. So look at the operation String variable after you got it from the console and see if it is "equalsIgnoreCase" (or just equals since these symbols don't have uppercase) to each one of the accepted operations. If it isn't equal to any of them then you should print out a message as it says. (Again with System.out.println).
You can then go into some if conditions and actually do the math if the operation equals one of the items. For example:
if(inputOperation.equalsIgnoreCase("+")){
double solution = inputInt1 + inputInt2;
//Need to do for all other operations. I didn't do the WHOLE thing for you.
}else if(NEED_TO_FILL_IN_THIS){
//Need to fill in the operation.
//You will need to have more else if conditions below for every operation
}else{
System.out.println("Your operation of '"+inputOperation+"' did not match any accepted inputs. Accepted input operations are '+','-','%','/' and '*'. Please try again.");
}
System.out.println("Your answer to the equation '"+inputInt1+" "+inputOperation+" "+inputInt2+"' is the following:"+solution);
That should get you started. Let me know if you still need further direction.
I hope that helps!
And to end with some fatherly advice: Again, it sounds like you are doing homework. This is all pretty well documented if you just know how to google. "Java get input from console". Or "Java check if String is equal to another string". Learning how to fish is so much more important than getting the fish. I suggest you do some catchup because if this is your homework and you are unsure then it seems like you are a bit behind. I don't mean to be rude. I am just trying to help you longer term.
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
Scanner f=new Scanner(System.in)
System.out.print("Enter the first number: ")
int firstNum=f.nextInt();
System.out.println();
System.out.print("Enter the operation: ")
String Op=f.nextLine();
System.out.println();
System.out.print("Enter the Second number: ")
int secNum=f.nextInt();
System.out.println();
int answ=0;
if(Op.equals("+"){
answ=firstNum+secNum;
}else if(.......){
}
hope it helps :)
To read the integers, use a Scanner
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the first number: ");
int firstNum = stdin.nextInt(); //first number
System.out.println("Enter the operation: ");
String operation = stdin.next(); //operation
System.out.println("Enter the second number: ");
int secondNum = stdin.nextInt(); //second number
doOperation(firstNum, secondNum, operation);
}
public static void doOperation(int firstNum, int secondNum, String operation)
{
if(operation.equals("+")
{
int result = firstNum + secondNum;
}
else if(...)
{
//etc
}
System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result);
}
Here is My Solution
package com.company;
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class Main {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
// write your code here
int First,Second,Resualt;
char operation;
System.out.println("Enter the first number: ");
First=scanner.nextInt();
System.out.println("Enter the operation:");
operation=scanner.next().charAt(0);
System.out.println("Enter the second number :");
Second=scanner.nextInt();
if (operation=='+'){
Resualt=First+Second;
System.out.println(First+" "+"+ "+Second+" = "+Resualt);
}
else if (operation=='-'){
Resualt=First-Second;
System.out.println(First+" "+"- "+Second+" = "+Resualt);
}
else if (operation=='*'){
Resualt=First*Second;
System.out.println(First+" "+"* "+Second+" = "+Resualt);
}
else if (operation=='%'){
Resualt=First%Second;
System.out.println(First+" "+"% "+Second+" = "+Resualt);
}
else {
System.out.println("Error");
}
}
}
Good Luck!!

Need a programs that asks user to enter 2 integers, check to see if 2nd number is multiple of first number

I cannot figure out why my if-else statements are not working properly. This is what I have so far:
import java.util.Scanner;
public class multiple {
public static void main (String[] args){
Scanner input = new Scanner (System.in);
int x = 4;
int y = 3;
int multiple = y % x;
while (multiple != 0){
System.out.println("Enter two integers: ");
x = input.nextInt();
y = input.nextInt();
if (multiple != 0)
System.out.println("Oops, sorry! The second integer is NOT a multiple of the first integer.");
else
System.out.println("Good Job! " + y + " is a multiple of " + x + "!");
}
}
}
You are not updating multiple after taking user input.Change your code like this.it should work.
import java.util.Scanner;
public class multiple {
public static void main (String[] args){
Scanner input = new Scanner (System.in);
int x = 4;
int y = 3;
int multiple = y % x;
while (multiple != 0){
System.out.println("Enter two integers: ");
x = input.nextInt();
y = input.nextInt();
multiple = y % x;
if (multiple != 0)
System.out.println("Oops, sorry! The second integer is NOT a multiple of the first integer.");
else
System.out.println("Good Job! " + y + " is a multiple of " + x + "!");
}
}
}
You must update your multiple variable every time you change x and y. What you have now checks if 4%3 is 0, every single time.
In other words, set multiple to y%x after you update x and y.
To add to what Prince and playitright said, I would ask to
check if the number entered by user does not equal zero. This is very important else you might encounter a runtime exception.
you are trying y%x and not x%y.
because the datatypes you selected are all int, thus x%y should also be checked.
assume,
x=3 and y=6, your solution works, but if we just reverse the values that is x=6 and y=3, the output is not correct.

Checking for negative values with scanner in

I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p

Categories

Resources