How got the reverse number? - java

I m not understanding the meaning of using this lines
this are on the while block.
import java.util.Scanner;
public class ReverseNumberWhile {
public static void main(String[] args){
int num = 0;
int reversenum = 0;
System.out.println("Enter your number and press enter: ");
Scanner input = new Scanner(System.in);
num = input.nextInt();
while(num != 0) {
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of input number is: " + reversenum);
}
}

There you go,commented :
while(num != 0)
{
reversenum = reversenum * 10; //This moves the reversenum attained in previous iteration to one higher place value
reversenum = reversenum + num%10; // num%10 gives you the last digit which is added to the existing reversenum
num = num/10; //This leaves the remaining digits removing rightmost
}

This code produces the number reversenum with the same digits as num, but in reversed order. For example, if num==12345, then reversenum==54321. It works by chopping the digits of num one-by-one, starting with the last one, and adding them to reversenum. The loop can be described as follows:
Append the last digit of num to reversenum (the first two lines).
Remove the last digit of num (the last line).
This repeats as long as there are any digits left in num, that is, while it's non-zero.
The first two lines can actually be written as a single line:
reversenum = reversenum * 10 + num % 10;
This way it actually makes more sense because you can see what's going on here: we take reversenum, shift its digits to the left (by multiplying by 10) and then add the last digit of num (which is obtained by num % 10).

Related

Why does my CalcOddIntegers method always return zero?

This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.
System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
if (array[i] % 2 != 0) {
count++;
}
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}
Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit
3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0
I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.
Remove the semi-colon (;) in the line
for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.
After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.

How to access the second character in a three-digit int?

System.out.println("Enter a three-digit number: ");
int num = sc.nextInt();
int digit1 = num / 100;
//int digit2 = ?
int digit3 = num % 10;
I need to find the 2nd digit in this three-digit number and then I have to check
if the number can be divided by each one of its digits. How can I get the 2nd digit?
So you could parse it to a string and get the numbers that way like:
int num = ...;
string numbS = Integer.toString(num);
char char1 = numbS.charAt(0);
int num1 = Character.getNumericValue(char1);
Or you could do it by dividing by 10 and then the remainder of ten:
int digit2 = (num / 10) % 10;
That is just (num / 10) % 10.
Let's say we have the base-10 integer x = 12345. We can perform a modulus operation x%10 to get a remainder of 5. That'll work for giving us the one's digit. What about the ten's place? Integer division x/10 gives us 1234. Then we can do the modulus operation and get the ten's place, x/10%10 = 4. To get the hundred's place, we divide by 100 first, and so on.
The general formula is x/10^(digit's index)%10, where a number's rightmost digit is located at index 0.

Credit card check using Luhn algorithim

I am trying to make an application in JAVA that will check whether a user-entered credit card number is valid.
These are the steps for modulus 10 to check:
Step1: 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.
Step2: now add all the single digit numbers from step1
Step3: add all digits in the odd places from right to left in the card number
Step4: sum the results from step 2 and step 3
Step 5: if the results from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. In this case, the card number is not valid – because 75 not divisible by 10.
My issue so far is that every card number I try (using valid numbers) I get told that it is invalid. I tried using the debugging tool and it looks like my value for sum is always wrong. I need help figuring out where I messed up in the calculations or if I am missing something.
public class CreditCardChecker {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
System.out.println("Enter credit card number to check validity: ");
System.out.println();
String cardNo = sc.next();
int sum = FindSum(cardNo);
if ((sum % 10) == 0) {
System.out.println("The card number is VALID.");
} else {
System.out.println("The card number is INVALID");
}
}
public static int FindSum(String cardNo) {
//CONVERTING CARD NUMBER INTO AN ARRAY
int[] digits = new int[cardNo.length()];
for (int i = 0; i < cardNo.length(); i++) {
digits[i] = Character.getNumericValue(cardNo.charAt(i));
}
//DOUBLE EVERY OTHER NUMBER FROM RIGHT TO LEFT
for (int i = digits.length - 1; i >= 0; i -= 2) {
digits[i] += digits[i];
if (digits[i] > 9) {
digits[i] = digits[i] - 9;
}
}
int sum = 0;
for (int i = 0; i < digits.length; i++) {
sum += digits[i];
}
sum *= 9;
return sum;
}
}
You have an error in your implementation of that step:
Step1: 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.
You start iterating with the last(nth) digit of the credit card number, while you should start with (n-1)th digit. That is, change:
for (int i = digits.length - 1; i >= 0; i -= 2)
to
for (int i = digits.length - 2; i >= 0; i -= 2)
Also, have in mind that your FindSum(String cardNo) method will only work for Strings without any spaces in them (which is how you may get your input).

Java- working with an integer

Write a static method called digitsInARow that takes an integer n as a parameter and that returns the highest number of digits that appear in a row in the base-10 representation of n. For many numbers the answer will be 1 because they don't have adjacent digits that match. But for a number like 3555585, the answer is 4 because there are four occurrences of the digit 5 that appear in a row. You are NOT allowed to use a String to solve this problem. You may assume that the value passed to the method is greater than or equal to 0.
public static int digitsInARow(int n) {
if (n / 10 == 0) {
return 1;
}
int count = 0;
int count1 = 0;
while (n > 0) {
int digit = n % 10;
int a = n / 10;
if (digit == a % 10) {
count++;
} else {
count1 = Math.max(count1, count);
count = 0;
}
n = n / 10;
}
return Math.max(count, count1);
}
I know the if statement is messed up. I am trying to figure out a way to compare consecutive digits WITHOUT using Integer class or String class. Any suggestions?
The problem with your code is that count keeps track of the current count, not of the highest count. You need to add a variable that tracks the highest count as well, and update it each time you process a digit, before resetting count back to zero.
Don't forget to update the highest count when you exit the loop, in case then-current count is greater than the previously found max.

Compare randomly generated number between user input

I am a cs student and i have an assignment that I'm not sure how to complete here is the prompt,
"Develop a Java console application for a simple game of guessing at a secret five-digit code (a random number from 10000 to 99999). When the user enters a guess at the code, the program outputs two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840 and the user guesses 83241, the digits 3 and 4 are in the correct positions. Thus, the program should respond with 2 (number of correct digits) and 7 (sum of the correct digits). Allow the user to guess until s/he gets it correct."
basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together. Here is my code so far.
Random rand = new Random();
int secretNumber = rand.nextInt(99999 - 10000 + 1) + 10000;
System.out.println(secretNumber);
Scanner consoleScanner = new Scanner(System.in);
int guess;
do {
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
if (guess == secretNumber)
System.out.println("****HOORAY! You solved it. You are so smart****");
else if (guess > 99999 || guess < 10000)
System.out.println("Guess must be a 5-digit code between 10000 and 99999.\n");
} while (guess != secretNumber);
any help would be greatly appreciated.
You have a number. I'm going to call it blarg. Let's say blarg is a double.
You also have a number called input.
String blargString = Double.toString(blarg);
String inputString = Double.toString(input);
ArrayList<Integer[]> indexNumberList = new ArrayList<Integer[]>();
int n = 0;
for (char c : blargString.toCharArray()) {
n++;
if (c == inputString.toCharArray()[n]) {
Integer[] entry = new Integer[2];
entry[0] = n;
entry[1] = Character.getNumericValue(c);
indexNumberList.add(entry);
}
}
Now you have a list of Integer pairs. Do what you will with it. For each pair, entry[0] is the location in the number, the index, and entry[1] is the value.
Integer.toString(int) returns the string representation of an integer. You can compare the strings returned from Integer.toString(secretNumber) and Integer.toString(guess) character-by-character to determine which digits differ.
Here's how I'd go about solving that problem. My solution is quick but probably naive. Convert the number the user enters and your generated number to strings and then to two arrays of 5 bytes each. Scan through the arrays and compare two corresponding bytes at a time. Let the user know that the position of a digit was guessed correctly if two corresponding bytes are equal. Below, I show you how you can get the array of bytes you need.
byte[] a = Integer.toString(guess).getBytes();
byte[] b = Integer.toString(secretNumber).getBytes();
So you have 2 5-digit numbers that you need to compare.
I would recommend you to do this with a loop:
//Make copies so we can modify the value without changing
// the original ones.
int tempGuess = guess;
int tempSecret = secretNumber;
//Create variables for the output
int numCorrect = 0;
int sumCorrect = 0;
for(int i = 0; i < 5; i++) //for each of the digits
{
//Get the last digit of each number and remove it from the number:
int lastGuess = tempGuess%10;
tempGuess/=10;
int lastSecret = tempSecret%10;
tempSecret/=10;
//Compare both digits:
if(lastGuess == lastSecret)
{
//Found a match: Increas number of found by one
numCorrect++;
//Add value of digit to sum
sumCorrect += lastGuess;
}
}
//numCorrect now contains the number of matching digits
//sumCorrect now contains the sum of matchig digits
The solution can be address like:
define an counter for the coincidences and an accumulator for the adition of those
make a loop through the guess and compare char by char if the input at any given char match the random number, if so:
increase counter by one and add to the accumulator the integer value of the char.
Example:
final String s1 = Integer.toString(secretNumber);
final String s2 = Integer.toString(guess);
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
counter++;
acumm = Character.getNumericValue(s1.charAt(i));
}
}
System.out.println("There is/are " + counter + " coincidences");
System.out.println("The addition of those is: " + acumm);
you could use integers, use modulus and divide to get the digit you want.
53840 % 100000 / 10000 = 5
53840 % 10000 / 1000 = 3
loop and compare

Categories