I'm randomly generating 3 digit numbers using java.util.Random(). The number of random 3-digit numbers that the system prints is controlled by user input. Here's the code:
//If/then statement for determining game type (determines 3 digit numbers)
if (gameType == 3)
//for loop to generate random numbers (numGames is how many 3 digit numbers to print)
for (int i = 1; i <=numGames; i = i + 1){
int ranNums = randomGenerator.nextInt((999 - 100) + 1) + 100;
//Print random numbers to user
System.out.println(ranNums);
sumNums = ranNums % 10;
Basically, I want the code to add the DIGITS that are printed from the random number generator. For example, if the ranNums output is 111 and 111, I want the variable sumNums to equal 6, not 222. With the code I have now, it only adds the last digit of each number, (in this case 1 + 1 = 2).
You could do this:
sumNums = (n / 100) + (n / 10 % 10) + (n % 10);
Related
I am new to Java and currently working on a small class assignment. The question is as follows:
Write a program that determines whether a bank account number with 10 digits or fewer passes a validation test; it requires that we extract the digits, right to left by:
Using the modulo operator to extract the right most digit
Using integer division to remove the right-most digit from the account number to obtain a new number without it.
Beginning with the 2nd right-most digit, moving right to left, double every other digit. If it produces a value greater than 9, subtract 9 from that value.
Form the sum of all products(new digits) and the unchanged digits.
if the sum doesn't end in 0, its invalid.
Check the validity of 5113 4765 12 and 65 1234 1234
Here is my code:
long account = Long.parseLong(JOptionPane.showInputDialog( null, "Enter account number: " ));
int sum = 0;
long digit;
//5113476512
//6512341234
String str_number = String.valueOf(account);
digit = account % 10;
account /= 10;
for(int i = str_number.length() -2; i >= 0; i --){
digit = account % 10;
account /= 10;
// account%=10;
// sum += digit;
digit *= 2;
if (digit > 9){
digit -= 9;
}
sum += digit;
}
// for(int x = 0; x < digit.length; x ++){
// sum += digit[x];
// }
if (sum % 10 != 0){
JOptionPane.showMessageDialog(null, "Account number invalid");
}
else{
JOptionPane.showMessageDialog(null, "Account number valid");
}
JOptionPane.showMessageDialog(null, sum);
But I feel it doesn't follow the requirements and might not be correct. Only one of the account numbers returns valid although I'm not sure if that is supposed to be so or not. Any ideas on how to go about this?
The following implementation using a boolean flag to detect the other number shows that both account numbers are invalid:
public static boolean isValid(long acc) {
System.out.print(acc + " -> "); // debug print
int sum = 0;
boolean other = false;
while (acc > 0) {
int digit = (int) (acc % 10);
acc /= 10;
if (other) {
digit *= 2;
if (digit > 9) digit -= 9;
}
System.out.print(digit + " "); // debug print
sum += digit;
other = !other;
}
System.out.println("sum = " + sum); // debug print
return sum % 10 == 0;
}
Tests:
System.out.println(isValid(5113476512L));
System.out.println(isValid(6512341234L));
Output:
5113476512 -> 2 2 5 3 7 8 3 2 1 1 sum = 34
false
6512341234 -> 4 6 2 2 4 6 2 2 5 3 sum = 36
false
Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.
Your code should be something like:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
So basically your question is how to calculate the numbers, right?
My first hint for you would be how to get the first, second and third value from a 2 or 3 digit number.
For example for 3 digits you can do int hundretDigit = (n - (n % 100)) % 100. Of course this is really inefficient. But just get code working before optimizing it ;)
Just think about a way to get the "ten-digit" (2nd number). Then you add them and if they equal the third one you write System.out.println(<number>);
EDIT:
For 2 digit numbers I will give you the code:
if(i >= 10 && i <= 99) {
int leftDigit = (i - (i % 10)) / 10;
if(leftDigit == (i % 10)) {
//Left digit equals right digit (for example 33 => 3 = 3
System.out.println(i);
}
}
Try again and edit your source code. If you have more questions I will edit my (this) answer to give you a little bit more help if you need!
I'm trying to create a method to validate a credit card number, but we have to process it as a string
heres some information about my task...
Credit card numbers follow certain patterns. A credit card must have between 13 and 16 digits.
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine if a card number is entered correctly or if a credit card is scanned correctly by a scanner. Almost all credit card numbers are generated following this validity check, commonly know as the Luhn check or the Modulus 10 check, which can be described as follows. For illustration, consider the card number 4388576018402625.
Double every second digit from right to left. If doubling of a digit results in a 2-digit number, add up the two digits to get a single-digit number.
2 x 2 = 4
2 x 2 = 4
4 x 2 = 8
1 x 2 = 2
6 x 2 = 12 (1+2= 3)
5 x 2 = 10 (1+0= 1)
8 x 2 = 16 (1+6= 7)
4 x 2 = 8
Add all the 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
5 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 37
Sum the results from step 2 and step 3 37 + 37 = 74
If the result from step is divisible by 10, the card number is valid; otherwise, it’s invalid. For example, the number 4388576018402625 is invalid, but the number 4388576018410707 is a valid Visa card; the number 6011000593748745 is invalid, but the number 6011000593748746 is a valid Discover card.
here's what I have so far
static void CreditCardValidator() {
System.out.println("enter a credit card number");
String temp = options.nextLine();
if (temp.length() < 13 || temp.length() > 16) {
System.out.println("Input is invalid");
}
// inside loop with char at command do all the math
int tmpdouble;
int sum = 0;
int counter = temp.length() - 1;
for (int i = temp.length(); i != 0; i--) {
char tmp = temp.charAt(i);
//tmp converted to int
tmpdouble = tmp * 2;
int firstDigit;
int secondDigit;
if (tmpdouble >= 10) {
firstDigit = i / 10;
secondDigit = i % 10;
sum = sum + firstDigit + secondDigit;
}
else if(tmpdouble <= 9) {
sum = sum + tmpdouble;
}
HELP HERE{
// need to have it do the same thing as above but for odd numbers
}
where do I go from there? ^^
Thanks
Don't roll your own. This algorithm is already provided via commons.
https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/CreditCardValidator.html
So, I want to find what numbers between 1 and 100 are divisible by 3 and 7. I got it to work, except for one of the numbers. For some reason, 3 % 3 is giving me 3 as a remainder, but 6 % 3 is giving me 0. This is my code:
public class factors
{
public static void main(System args[])
{
//Variables
int integer, remainder;
//Displays header
System.out.print("Integers less than 100 that are \nevenly divisible by 3 or 7");
//Loops through each integer
for (integer = 1; integer <= 100; integer++)
{
remainder = integer % 3; //determines if 3 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 3");
}
remainder = integer % 7; //determines if 7 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 7");
}
}
}
}Does anyone know why this isn't working for the number 3?
You code is actually doing
remainder = 3 % 7; // equals 3.
The best way to determine why your code is not doing what you think is to step through your code using a debugger.
All the multiples of 3 & 7 will be multiples of 21, i.e. 21, 42, 63, 84.
Your 3 is getting tacked onto the end of the line of text above. You'll be seeing
Integers less than 100 that are
evenly divisible by 3 or 73
because you wrote print instead of println for this line of text. The % operator is working just fine, and 3 % 3 is indeed 0, not 3.
You are not outputting a remainder - you are displaying integer. So for 3 it should print 3.
Make you print statements more definite:
System.out.println(integer + " is divisible by 3"); // for the first `if`
and
System.out.println(integer + " is divisible by 7"); // for the second `if`
This should clear your confusion.
Your logic prints number divisible by 3 or 7.
Firstly, your code can be shortened to:
//and
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 7 == 0) {
System.out.println(i);
}
}
//or
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 || i % 7 == 0) {
System.out.println(i);
}
}
Also I note you're not declaring a type for your integer, remainder variables. I didn't attempt to recreate with those issues; start by solving that.
How to generate an odd Random number between a given range..
For Eg: For range between 1 to 6 ..
Random No is 3 or 1 or 5
Method for Generating Random No :
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
Refer How do I generate random integers within a specific range in Java?
Method For Generating Odd Random No :
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
if(Random_No%2 ==0)
{
if((Max%2)==0)&&Random_No==Max)
{
Random_No = Random_No - 1;
}
else{
Random_No = Random_No +1;
}
}
This Function will always convert 2 into 3 and not 1
Can we make this a more random function which can convert 2 sometimes into 3 and sometimes into 1 ??
Assuming max is inclusive, I'd suggest the following:
if (Max % 2 == 0) --Max;
if (Min % 2 == 0) ++Min;
Random_No = Min + 2*(int)(Math.random()*((Max-Min)/2+1));
It results in even distribution among all the odd numbers.
If you want to include randomness in the direction as well use random number for the same.
int randomDirection = Min + (int)(Math.Random()*((Max-Min)+1));
if(randomDirection%2==0) { // any condition to switch the direction
Random_No = Random_No + 1;
} else {
Random_No = Random_No - 1;
}
Instead of generating a random number between 0 and 6, generate one between 0 and 5 and round up to the nearest odd number, that way you'll have a perfect distribution (33% for each possibility (1, 3, 5))
To do so you need to generate a second pseudo-random number to add or substract 1
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
repartitionNumber =(int)(Math.Random()*((2)) // between 0 and 1
if(Random_No%2 ==0)
{
if(Random_No+1<=Max && Random_No-1>=Min)
{
if(repartitionNumber==0)
Random_No = Random_No + 1;
else
Random_No = Random_No - 1;
}
else if(Random_No+1<=Max)
Random_No = Random_No + 1;
else if (Random_No-1>=Min)
Random_No = Random_No - 1;
}
I wonder why other answers all use the int cast to generate the random number. Why not generate random integer directly, which is more accurate than real number way?
Random rn = new Random();
if(maximum % 2 == 1) maximum = maximum + 1; // turn right bound to even
if(minimum % 2 == 0) minimum = minimum - 1; // turn left bound to odd
int range = (maximum - minimum + 1) / 2;
int randomNum = rn.nextInt(range) * 2 + minimum;
To generate an odd number from a integer you can use n * 2 + 1 Really you are generating random numbers and applying a transformation afterwards
int num = min / 2 + random.nextInt((max + 1) / 2 - min / 2);
num = num * 2 + 1;
This will work even if the range is [1,5] [2,5] [2,6] [1,6]
Mathematically the numbers will not gain anything by rounding up or down in the last step. Instead the first and the last number have a 50% lower chance to get picked over all the other numbers.
Stick with CrazyCasta's or J.A's solution.
How about checking the return from Math.random() as a floating number. If its int part is an even number, then convert up/down based on its floating part. Like:
assume Math.random() returned x.y; if x is even, return (y>=0.5)?(x+1):(x-1)
Will this randomized a little?
Let the rouding above or below depend on a random epsilon.
Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
if(Random_No%2 ==0)
{
if((Max%2)==0)&&Random_No==Max)
{
Random_No = Random_No - 1;
}
else{
epsilon = Math.Random();
if(epsilon > 0.5)
Random_No = Random_No + 1;
else
Random_No = Random_No - 1;
}
}
In Java 1.7 or later, I would use ThreadLocalRandom:
import java.util.concurrent.ThreadLocalRandom;
// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
if (min % 2 == 0) ++min;
return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}
// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
if (min % 2 != 0) ++min;
return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}
The reason to use ThreadLocalRandom is explained here. Also note that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.