I'm trying to create my fist java application with an if statement that will take an integer (e.x 22) and find out if its sum is equal when multiplied and subtract (e.x 2*2=4 and 2+2=4) or if its not.
Though i can't figure out how to do the if decision. can someone point out how to do that?
thank u
package 1;
import java.util.Scanner;
public class 1
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int x;
int y;
System.out.print( "Enter a number from 10 to 99: " );
x = input.nextInt();
if ( x >= 10 && x <= 99 )
{
x= x % 10;
x= x / 10;
}
else
{
System.out.println( "you must enter a number from 10 to 99" );
}
}
}
You just need to assign them to different variable and check for the condition
if (x >= 10 && x <= 99) {
int first = x / 10; // Take out the first digit and assign it to a variable first
int second = x % 10; // Take out the second digit and assign it to a variable second
if (first * second == first + second) { // Check for your condition, which you mentioned in your question
System.out.println("Yep, they match the condition"); // If it satisfies the condition
} else {
System.out.println("Nope, they don't match the condition"); // If it doesn't satisfy the condition
}
}
P.S: You question said multiplied and subtract but the example just after the example was (e.x 2 x 2=4 and 2+2=4). I went with the ex.
try
import java.util.Scanner;
public class One {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x;
int y;
System.out.print("Enter a number from 10 to 99: ");
x = input.nextInt();
if (x >= 10 && x <= 99) {
y = x % 10;
x = x/10 ;
if(x* y== x+ y)){
System.out.println("Sum and product are equal" );
}
else
System.out.println("Sum and product are not equal" );
} else {
System.out.println("you must enter a number from 10 to 99");
}
input.close();
}
}
Related
world! :)
It is my third programming day (please, be lenient...)
Code was intended to find out whether the sum (when it reaches 1 digit only) of digits of number 123456789 can be divided by 9.
I cannot find how to make second 'else' work - any help and explanation why so would be highly appreciated:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int n=123456789;
System.out.println(n);
do{
private static int sumDigits(int n)
int s=sumDigits(n);
if (s < 10) ;
{
if (s == 9) System.out.println("divides by 9");
else System.out.println("doesn't divide by 9");
break;
}
else n = s;
}while (true);
}
The function, sumDigits should return the sum of digits of the parameter, n. For this, you can add each digit of n to a variable, sum initialized with the value, 0. The value of x % 10 gives you the last digit of x. Every time you add the last digit of n to sum, divide it by 10 to make it one digit less from the end.
You need a loop to pass the sum of digits to sumDigits until the sum of digits become a single digit. I suggest you use a do-while loop which guarantees its body to be executed at least once.
At the end of the loop mentioned in point#2, you will have the sum of digits as a single digit. The final thing that you need to do now is to check if this sum is divisible by 9.
Note that if x % y == 0, then x is divisible by y.
Demo:
public class Main {
public static void main(String[] args) {
int n = 123456789;
int singleDigitSum = 0;
int divisibleBy = 9;
do {
singleDigitSum = sumDigits(n);
n = singleDigitSum;
} while (singleDigitSum > 9);
if (singleDigitSum % divisibleBy == 0) {
System.out.println("The single digit sum is divisible by " + divisibleBy);
} else {
System.out.println("The single digit sum is divisible by " + divisibleBy);
}
}
private static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Output:
The single digit sum is divisible by 9
Note: Java does not allow defining a method/function inside another method/function. You have done this mistake by defining the function, sumDigits inside the method, main.
Try the code below:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int number = 123456789;
int sumOfDigits = sumDigits(number);
if (sumOfDigits%9 == 0) {
System.out.println("divides by 9");
return;
}
System.out.println("doesn't divide by 9");
}
public static int sumDigits(int num)
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
I need to write a program that allows the user to enter a 13-digit ISBN as a single integer.
The program should then determine and show whether the number is valid according to the formula above. It also needs to print an error message if the user tries to enter a number longer than 13 digits.
Below is the code I am working on.
I'm new to java and I don't understand where it went wrong. I also don't seem to figure out how to get the length of a long variable.
import java.util.Scanner;
public class ISBNChecker{
public static void main(String [] args){
long isbnNumber;
long isbnTotal;
long x;
Scanner scnr = new Scanner(System.in);
isbnNumber = scnr.nextLong();
while (isbnNumber > 0) {
x = isbnNumber % 10;
isbnTotal = total + x;
isbnNumber = isbnNumber / 10;
x = isbnNumber % 10;
isbnTotal = total + (3 * x);
isbnNumber = isbnNumber / 10;
}
if (isbnTotal % 10 = 0) {
System.out.println("Number is valid!");
}
else {
System.out.println("Number is invalid.");
}
}
}
Fix your (own) current code
In your original code, you have a couple of tiny errors:
isbnTotal = total + x;
total is not declared anywhere, and isbnTotal is not initialized.
if (isbnTotal % 10 = 0) {
You need to compare with double =, a single one is for assignation, double == is for comparison.
Separate your code into modules to improve it
... determine and show whether the number is valid according to the formula above.
I think that you forgot to write the formula, but according to Wikipedia, is this one:
So, you need to check if the sum of all digits multiplied by their weight (alternating 1 and 3) is a multiple of 10.
So, first of all we need to get the sum of all digits and multiply each digit by 1 or 3 alternating (backwards as we're gonna be using the modulo operator).
So, we need something like this:
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
Let me explain what the above code does, is make use of the ternary operator (CTRL-F on the page to read about it), to determine if we need to multiply by 1 or 3, in the formula it starts with 1, so the easiest way to do it is by checking if the current index is even or odd, if even, multiply by 1, otherwise multiply by 3, and adds that number to the sum.
Then it divides the current number by 10.
Then all we have to do is check if the sum of all digits multiplied by their respective weights is a multiple of 10.
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
And just before that, if the given number doesn't have 13 digits, we say that it isn't.
So, in the end our program should be something like:
public class ISBNChecker {
public static void main(String[] args) {
String isbnNumber = "978030640615";
if (isbnNumber.length() != 13) {
System.out.println("ISBN Number is invalid");
return;
}
if (isAValidISBN(Long.parseLong(isbnNumber))) {
System.out.println(isbnNumber + " is a valid ISBN");
} else {
System.out.println(isbnNumber + " is not a valid ISBN");
}
}
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
}
And if we take the Wikipedia value, we get this output:
9780306406157 is a valid ISBN
I don't understand your question clearly, but I suppose what you want to do is validate if the number provided by the user has 13 digits or not, you could do this:
public static void main(String[] args) {
String userNumber;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter ISBN number, 13 digit");
userNumber = scnr.nextLine();
/*regular expression to verify that it contains only 13 digits*/
if(userNumber.matches("^[0-9]{13}$")) {
System.out.println("Number is valid");
} else {
System.out.println("Number is invalid");
}
}
First of all, what do you mean with:
according to the formula above.
What formula do you mean? And Second, to get the length of an long or integer just do:
int length = ("" + isbnNumber).length()
And btw, when you are doing an if statement do "==" instead of "=".
if (isbnTotal % 10 = 0) {
…should be:
if (isbnTotal % 10 == 0) {
Or better, reverse so compiler would have caught your typo.
if (0 == isbnTotal % 10) {
So I'm practicing writing simple Java programs. I made one to change binary numbers to decimal. In last loop below all if(){}'s my program jumps to else without reason to do so. I've changed this last else to another if statement and program is running properly. But I wonder HOW it is possible that the first program is jumping to else. What property of if-else statements is making that?
Here is the code and outputs of both programs:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
}
else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
issue with 6 digit
issue with 4 digit
issue with 3 digit
issue with 1 digit
90.0
#### AND SECOND:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48){ //if digit from binary number is 0, just skip to next power of 2
power++;
}
if(x!=49 && x!=48) {System.out.println("issue with "+(i+1)+" digit"); //if digit from binary number is not 1 or 0 -> give error
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
90.0
Because in your first program else belongs only to second if statement, that's mean all values that not pass this if will go to else. In your second program you modified your statement. You can also try to modify your first program to this, it should give you the same result:
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
} else if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
} else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
} return result;
}
currently im trying to find the divisibility for a number the user inputs and the number should be divisible from x to y
example: 2520 is divisible by all numbers from 1-10.
so here is what i done so far, so clearly i coded it in a bad way, can anyone do better?
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int temp = 0,x,y,num;
System.out.println("enter the number to check for");
num = kb.nextInt();
System.out.println("enter the starting number");
x = kb.nextInt();
System.out.println("enter the ending number");
y=kb.nextInt();
while(x >= y){
System.out.println("starting num must be less then the ending num,re-enter the starting num.");
x = kb.nextInt();
System.out.println(" now enter the ending number, must be greater then the starting num");
y=kb.nextInt();
}
while ( num % x == 0 && x < y){
x++;
}
if ( x == y){
System.out.println("the number "+ num + " is divisble by this range.");
}
}
}
Write it as a helper method:
public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) {
for (int divisor = fromDivisor; divisor <= toDivisor; divisor++)
if (dividend % divisor != 0)
return false;
return true;
}
Some things to consider:
It would be more user-friendly if you accepted the integers in either order. If the first is larger than the second, just go from the second to the first. So, something like:
int swapInt;
if (x > y)
{
swapInt = x;
x = y;
y = swapInt;
}
It would be more user-friendly if you accepted the same integer for the start and end. The user might want to just check one number. (How would you change your code to do this?)
It looks like you accept any integers, including zero and negative integers. Will your program still work? If not, what would you have to change?
I don't understand why only my while statement is working and it does not move on to the for statement for the valid integer.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
long posNumber;
long x;
long fact = 1;
do {
System.out.print("Enter a number between 2 and 15: ");
Scanner in = new Scanner(System.in);
posNumber = in.nextLong();
} while (posNumber >= 2 || posNumber <= 15);
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
}
You should try something like, if you plan to get numbers in a loop:
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a number between 2 and 15: ");
posNumber = in.nextLong();
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
} while (posNumber >= 2 || posNumber <= 15);
Or you can change the condition (in case to run it just once):
while (posNumber < 2 || posNumber > 15);
You want your program to continue asking the user if the number is invalid. That means if it is less than 2 or greater than 15. Replace your while condition with:
do {
...
} while (posNumber < 2 || posNumber > 15);
If the user enters a 1, posNumber < 2 will evaluate to true causing the loop to repeat and ask for a new number.
If the user enters 3, both posNumber < 2 and posNumber > 15 will evaluate to false and the loop will break and then your for loop will execute.