I'm trying to ask for an integer between 4 and 10 from the user. If they answer out of that range it will go into a loop. When the user inputs the number correctly the first time it will not break and continues to else statement. If the user inputs the number correctly during the else statement it will properly break.
How can I get it to break if input is correct the first time around?
**I am very much a beginner at java and do apologize if it is something silly i'm missing here.
public int companySize() {
int ansCompany;
do {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please input the company size"));
if ( ansCompany <= 4 && ansCompany <= 10 ) {
break;
} else {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please enter a valid company size"));
if ( ansCompany <= 4 && ansCompany <= 10 ) {
break;
} // ends nested if condition
} //ends else
}//ends do
while ( ansCompany < 4 || ansCompany > 10);
return ansCompany;
}// ends public int companySize()
I'm calling it from main as follows:
public static void main(String[] args) {
UserInput getResult = new UserInput();
int company_size = getResult.companySize();
}// ends main
I am not sure why you need two identical dialogs if the user would write the wrong value the first time, since in the end only one value will be returned (ansCompany).
By setting the do-while statement to the break condition (less than 4 or greater than 10) it will loop until the user inputs the correct number.
public int companySize() {
int ansCompany;
do {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please input the company size"));
} while (ansCompany < 4 || ansCompany > 10);
return ansCompany;
}
while ( ansCompany < 4 || ansCompany > 10); is anything below 3 OR higher than 11
You want while ( ansCompany >= 4 && ansCompany <= 10);
Note: The reason you want this choice ^^^^ is because if the input is greater than > or equal = making >= than means 4 and above. Likewise for less than < or equal = making <= than means anything less than 10
The || means OR. This mean the input must be greater than 4 or less than 10. If the answer is 11, It passes the first condition and therefore passes the if statement. Likewise with a 3, it passes the less than 10 condition.
&& mean AND, and therefore must pass the first condition, AND the second condition.
Your if statements also are wrong in this sense;
if ( ansCompany <= 4 && ansCompany <= 10 ) {
should be
if ( ansCompany >= 4 && ansCompany <= 10 ) {
I would rather use a recursive function:
Version1: In short:
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog("Please input the company size"));
return (result >= 4 && result <= 10) ? result : companySize();
}
Version 2: But you also can use static constants
/* don't be afraid of shared constants; sometimes they're very "useful idiots" */
/*public*/ static final int MIN = 4;
/*public*/ static final int MAX = 10;
/*public*/ static final String MESSAGE = "Please input the company size";
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog(MESSAGE));
return (result >= MIN && result <= MAX) ? result : companySize();
}
Version 3: And if you want to show an error message:
/* don't be afraid of shared constants; sometimes they're very "useful idiots" */
/*public*/ static final int MIN = 4;
/*public*/ static final int MAX = 10;
/*public*/ static final String MESSAGE = "Please input the company size";
/*protected*/ static final String ERROR_MESSAGE = "Please input a valid company size";
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog(MESSAGE));
return (result >= MIN && result <= MAX) ? result : companySize(ERROR_MESSAGE);
}
private int companySize(String errorMessage) {
final int result = Integer.parseInt(JOptionPane.showInputDialog(errorMessage));
return (result >= MIN && result <= MAX) ? result : companySize(ERROR_MESSAGE);
}
and
public static void main(String[] args) {
UserInput getResult = new UserInput();
int company_size = getResult.companySize();
}
Related
I want to check if a number if binary or not in decimal numbers but it didnt work
from numbera 1 to n.
for example from 1 to 10 we have 2 decimal numbers that contains 0,1.How can i change it?
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
int r = 0, c = 0, num, b;
int count=0;
Scanner sl = new Scanner(System.in);
System.out.println("Enter a number");
num = sl.nextInt();
for (int i = 1; i <= num; i++) {
if ((i % 10 == 0) || (i % 10 == 1))
c++;
r++;
i = i / 10;
}
if (c == r)
count++;
else{
}
System.out.println(count);
}
}
I am not a java dev so maybe my answer is not good.But you can use your number as str then check if the str is constituted only by 0 and 1
maybe this could help: : How to check if only chosen characters are in a string?
have a nice day
Here's how you can do it in an elegant way ...
// Function to check if number
// is binary or not
public static boolean isBinaryNumber(int num)
{
if(num == 1 || num == 0) return true
if (num < 0) return false;
// Get the rightmost digit of
// the number with the help
// of remainder '%' operator
// by dividing it with 10
while (num != 0) {
// If the digit is greater
// than 1 return false
if (num % 10 > 1) {
return false;
}
num = num / 10;
}
return true;
}
Here, will use 2 loops, one for range and one for checking if it's binary or not.
Instead of c and r, we will use flag and break in order to skip unnecessary iteration.
int count=0;
boolean flag = true;
for(int i=1;i<=num;i++)
{
for(int j=i;j>0;j=j/10)
{
// if remainder is not 0 and 1, then it means it's not binary
// so we set flag as false
// and using break to break out of the current(inner) loop, it's no longer needed to check remaining digits.
if (j%10 > 1)
{
flag = false;
break;
}
}
// if flag is true, that means it's binary and we increment count.
// if flag is flase, that means it's not binary
if(flag)
count++;
// here we reset flag back to true
flag = true
}
System.out.println(count);
You can also do as #jchenaud suggested. converting it to string and check if it only contains 0 and 1.
Currently doing a challenge called number to words, I have created 2 methods, one which
deals with comparing values individually so that it can print out it's string value(method called numberToWord), another method called reverse which basically re-orders the values so that it is printed in a correct sequence, for example:s
Step One 567 --> Step 2, it will be converted into 765 --> Step 3, reverse method will then convert it back to 5,6,7 individually so that it can compare the values with the if statements. However, i have tried so many things to getting this to work, i managed to make it to step 3 but when i try to return the value it gives me 3 random values before it converts e.g = 7,6,7...5,6,7, i am unable to figure out how to remove the first 3 values and return just the last three values so that it can be compared in the numberToWords method.
package com.company;
public class Main {
public static void main(String[] args) {
numberToWords(567);
}
public static void numberToWords(int number) {
int lastDigit = 0;
int digit = number;
int reverseDigit = 0;
if (number < 0) {
System.out.println("Invalid Value");
}
for (int i = 0; i < digit; i++) {
//so we are taking the last digit from 567 per iteration
lastDigit = digit % 10;
//we are then dividing the digit by 10 each time so we can get another last digit
digit /= 10;
//i will now try to essentially get down to the final number which will be flipped
reverseDigit = (reverseDigit * 10) + lastDigit;
//checking values
System.out.println(reverse(reverseDigit));
// if (reverse(reverseDigit)== 0) {
// System.out.println("Zero");
// } else if (reverse(reverseDigit) == 1) {
// System.out.println("One");
// }else if (reverse(reverseDigit) == 2) {
// System.out.println("Two");
// }else if (reverse(reverseDigit) == 3) {
// System.out.println("Three");
// }else if (reverse(reverseDigit) == 4) {
// System.out.println("Four");
// }else if (reverse(reverseDigit) == 5) {
// System.out.println("Five");
// }else if (reverse(reverseDigit) == 6) {
// System.out.println("Six");
// }else if (reverse(reverseDigit) == 7) {
// System.out.println("Seven");
// }else if (reverse(reverseDigit) == 8) {
// System.out.println("Eight");
// }else if (reverse(reverseDigit) == 9) {
// System.out.println("Nine ");
// }
if (lastDigit == 0) {
System.out.println("Zero");
} else if (lastDigit == 1) {
System.out.println("One");
} else if (lastDigit == 2) {
System.out.println("Two");
} else if (lastDigit == 3) {
System.out.println("Three");
} else if (lastDigit == 4) {
System.out.println("Four");
} else if (lastDigit == 5) {
System.out.println("Five");
} else if (lastDigit == 6) {
System.out.println("Six");
} else if (lastDigit == 7) {
System.out.println("Seven");
} else if (lastDigit == 8) {
System.out.println("Eight");
} else if (lastDigit == 9) {
System.out.println("Nine");
}
}
}
public static int reverse (int a){
int lastDigit = 0;
for (int i =0; i < a; i++) {
lastDigit = a % 10;
a /= 10;
//testing values here
//System.out.println(lastDigit);
//sout in loop gives us 567
}
return lastDigit;
}
}
If I understand what you need correctly, you don't need that much code. Just print the reminder of division by 10 and then divide by ten for then next iteration until you get zero.
enum Numbers {
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine;
}
private static void process(int number) {
do {
final int digit = number % 10;
System.out.println(Numbers.values()[digit]);
number /= 10;
} while (number > 0);
}
First use an enum since you can use it like an array but easier to declare. Then with the number you get, first get the reminder over ten. For any integer expressed as decimal the reminder over ten is the last digit. Since you have to print the last digit in the first place, just print it. Then replace number with number divided by ten. That will discard the last digit (the one just printed out) because this is an integer division. I mean, 1234 over 10 is 123.4 but because these are integer it gets truncated to 123. So now loop and the last digit will be printed again (but now it will be the first to the left due to the division). At some point, after printing the first digit of the original number you will have a one digit integer (i.e. 7) divided by ten which results in zero (because it would be 0.7 but it's an integer division).
You need to add some preconditions like the negatives.
I think you have the right idea of doing remainder division for numberToWords() and reverse().
But I think you're condition for exiting the for loop is wrong
for (int i = 0; i < digit; i++)
It will exit before you get all the digits. You want to loop until digit is 0, since you want to remainder divide UNTIL there's no more to divide ( meaning digit is 0).
so
for(int i = 0; digit != 0; i++){
...
}
while loop might be better than a for a loop since you're not using i anyways.
while(digit != 0){
...
}
It also depends on which IDE you're using but IntelliJ and eclipse can do a line by line debug so you see which line is causing issues.
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 Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}
It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.
if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance
I'm working on a school assignment that checks whether a credit card number that is entered is valid or not, using Luhn's Algorithm.
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388 5760 1840 2626):
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
Now add all single-digit numbers from Step 1: 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number: 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3: 37 + 38 = 75
If the result from Step 4 is divisible by 10 the card number is valid; otherwise, it is invalid. For example, the number 4388 5760 1840 2626 is invalid, but the number 4388 5760 1841 0707 is valid.
I need to write this program using the methods in the code I have written:
public class CreditCardValidation {
public static void main(String[] args, long input) {
Scanner numberinput = new Scanner(System.in);
System.out.println("Enter a credit card number as a long integer: ");
long cardnumber = numberinput.nextLong();
if (isValid(input) == true) {
System.out.println(numberinput + " is valid.");
} else {
System.out.println(numberinput + " is invalid.");
}
}
public static boolean isValid(long number){
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
return (total % 10 == 0) && (prefixMatched(number, 1) == true) &&
(getSize(number)>=13) && (getSize(number)<=16);
}
public static int sumOfDoubleEvenPlace(long number) {
int doubledevensum = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubledevensum += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubledevensum;
}
public static int sumOfOddPlace(long number) {
int oddsum = 0;
while (number <= 9) {
oddsum += (int)(number % 10);
number = number % 100;
}
return oddsum;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int)(number / 10);
return firstDigit + secondDigit;
}
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int)getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
I just started learning how to program two months ago so I am fairly new to this. The program doesn't compile and I don't know why and what I have to do to fix this. I know there are similar topics already posted regarding this and I have been using this post to help guide me a bit. Can someone help point a student in the right direction and let me know what I'm doing wrong?
Your program isn't compiling because this line:
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
since sumOfDoubleEvenPlace and sumOfOddPlace are functions, you must use them as such:
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
In the function isValid you are trying to add two variables which do not exist. However you have defined them as functions and to use them as functions you must call them as functions using
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);