I am trying to make a program that uses three digit numbers to identify items and I am trying to use something like the charAt method for integers or something. Im not too sure. Im a beginner and I apologize i just need help. Also I need a bit of help to use an if statement and relational operators. Im trying to do if the last digit in the number is less than 5 then it is {item} and if its greater than 5 then its this {item}. Something like that. Thank you so much in advance.
String number;
System.out.println("Enter three digit number: ");
number = in.nextLine();
switch (number.charAt(0))
{
//stuff
}
if (number > 5)
{
//it is this item
{
else
{
//it is the other item
{
There are at least two ways you can do it:
String number = in.nextLine();
char c = number.charAt(i); // i is the position of digit you want to retrieve
int digit = c - '0';
if you want to get ith digit from the end of an Integer, do:
int digit = 0;
while(i > 0) {
digit = n%10;
n /= 10;
--i;
}
To check the last digit of a base-10 number, use the remainder operator:
if (number % 10 < 5) {
// handle last digit is 0-4
} else {
// handle last digit is 5-9
}
Related
The following question was asked in my last interview (yesterday), and I'm trying to solve it since then (couldn't solve it in the interview).
Sorry for any grammar mistakes or any logical mistakes, I don't have the question, it was written by memory:
You are given a number in a string format, for example: "14438832066".
You got to sum up the consecutive equal digits in that number. If no
consecutive equal digit was found, just add the digit to the result.
for example: solution(19938832066) => 11831632012
Explanation: first digit is 1.
The second and third digits are both 9 which means they will turn into 18 in the result string.
So on
with the rest of the digits (as you can see, the last 2 digits are both 6 which means they will turn into 12 in the result string).
You are required to do that for the result string as well, if needed, until no equal consecutive digits are found in the number.
Example:: number: 14438832066 solution( "19938832066") ->"11831632012" -> "2831632012"
Explanation: first result is 11831632012, but then you can see that there are still equal consecutive digits : the first and the
second digits are both 1. So process that number as well.
You are given a string and must return a string.
My solution:
I couldn't write the solution, I don't know why. It's a pretty simple question, I thought going recursive at first but didn't want to complex things.
I wrote 2 helper methods:
one that returns a boolean whether the number consists of equal consecutive digits.
one that actually makes the business logic:
turn the string into a char array
create a counter that will count instances of the same digit - (int counter = 1).
loop on the array from the first to the one before the last element :
inside the loop:
//equal digit was found - increment counter and continue to next digit
if char[i] == char[i+1] then counter++
//calculation in case we are done counting the same digit
else if counter > 0 then result.append(counter*digit[i])
// if no consecutive equal digit was found
else result.append(digit[i])
end loop: return result
Problems I had:
I created the counter inside the loop, so each iteration it got rested. took me few minutes to realize.
I had troubles realizing that 'int(digit[i])' doesn't give me the numeric value of the char, it gives the ASCII value. I had to use "Character.getNumericValue" (don't remember the exact name of the method).
Because of these problems, it took me 45 minutes to write the solution which in the end didn't even work.
I'll be glad to get a working solution, and even better - to get any feedback and tips on my solution and what, in your opinion, were my mistakes.
Thank you.
Your pseudo-code seems alright, as far as it goes. What's missing is that you don't repeatedly check the result string to see if another pass is required. I also show how you don't need to remember the API to convert a character to a digit; if you know the digits are decimal, you can interpret them yourself. As an interviewer, I would accept that there is an API that you can't precisely remember or your home-brew solution as equally valid.
String transform(String number) {
while (true) {
String result = collapse(number);
if (result.equals(number)) return result;
number = result;
}
}
private static String collapse(String number) {
StringBuilder result = new StringBuilder();
for (idx = 0; idx < number.length(); ) {
int mark = idx;
int digit = digitAt(number, idx++);
while (idx < number.length() && digitAt(number, idx) == digit) ++idx;
result.append((idx - mark) * digit);
}
return result.toString();
}
private static int digitAt(String num, int index) {
char ch = number.charAt(index);
if (ch < '0' || ch > '9') throw new IllegalArgumentException();
return ch - '0';
}
The preceding is a naïve approach that transforms the string until there are no changes. I suspect there might be a more "elegant" approach that works from left to right through the input in a single pass, but it would take some thought, and I probably couldn't come up with that in an interview.
Here's an algorithm that uses recursion and a for-loop to add consecutive equal digits. I think the code is pretty self-explanatory but please ask if you have any queries.
public static String addConsecutiveDigits(String number) {
char[] arr = number.toCharArray();
StringBuilder result = new StringBuilder();
boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits
for (int i = 0; i < arr.length; i++) {
int digit = arr[i] - '0'; //Subtracting ascii values to get integer values
int newNumber = digit;
if (i != arr.length - 1) {
int nextDigit = arr[i + 1] - '0';
if (digit == nextDigit) { // check if the digits are consecutive digits
newNumber = digit + nextDigit;
i++; // increment i as we have already added the i+1 digit
foundConsecutive = true;
}
}
result.append(newNumber);
}
if (!foundConsecutive) // if no consecutive equal digits were found then return the result;
return result.toString();
else // recurse to check for more consecutive equal digits
return addConsecutiveDigits(result.toString());
}
I'm not a Java guy, so this code might not be ideal but I would do something like this:
public String solve(String input)
{
String result = "";
int i = 0;
while (i < input.length())
{
var first = input.charAt(i);
if (i == input.length() - 1){
result += first;
break;
}
var second = input.charAt(i + 1);
if (first == second){
result += (Character.getNumericValue(first) + Character.getNumericValue(second));
i += 2;
} else {
result += first;
i += 1;
}
}
return result;
}
For the second part, I would just run the function in a loop until the result matches the input.
I'm trying to count the digits of an integer with java, it supposed to give 4 but instead I get 1 .
I don't know if I did something wrong, if someone could help.
Here's the code :
public static void main(String[] args) {
int n = 4781, i = 0;
while (n != 0) {
n %= 10;
n /= 10;
i++;
}
System.out.println(i);
}
The n %= 10 is unnecessary and in fact the source of the problem here. If you remove it, the code will work.
Usually when you do these kinds of "do something for each digit" you use % 10 to find the current digit a little bit like this:
int digit = n % 10;
System.out.println("The current digit is " + digit);
But in your case you don't actually care what the digits are, you only care how many there are, so there's no need to do % 10 at all.
And the way you did it you overwrote n (which is supposed to hold the current state of the number) with the current digit and then divided by 10. So no matter what the first digit is, this will never return a number bigger than 1.
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
Is there any better logic that can be applied to magic numbers?
Or is there a magic number that I am missing out on?
Please help me out with this simplest working code!
A Magic number is a number whose sum of digits eventually leads to 1.
Example#1: 19 ; 1+9 =10 ; 1+0 = 1. Hence a magic number.
Example#2: 226; 2+2+6=10; 1+0 =1. Hence a magic number.
Example#3: 874; 8+7+4=19; 1+9=10; 1+0=1. Hence a magic number.
boolean isMagic ( int n ) {
return n % 9 == 1;
}
Well, I'm not 100% that the code you placed would work to get a "magic number", but my approach to the problem would be different.
First, I'd receive a String, so that I can get the different digits of the number with a String.charat.
Then I'd use a while cycle to sum the numbers until it gets a single digit number, then check if it's 1.
The code would be
boolean isMagicNumber(String number) {
int[] digits = new int[number.length()];
int sum = 99;
while(sum/10 >= 1) {
sum = 0;
for(int i = 0; i < number.length(); i++) {
sum += Integer.parseInt(""+number.charAt(i));
}
if(sum == 1) {
return true;
}
}
return false;
}
There might be a better solution, but this is what I'd do to solve the problem.
Hello everyone I was having some issue splitting up a user input number using printf (I do have to use printf). My problem is that when I put in say the number 12345 it will print the integers on five separate lines, and also has them in the reverse order. So it would look something like this when I put in the integer 12345:
5
4
3
2
1
But without the spaces (I need those as well). I want it to print like this: 1 2 3 4 5.
Here is the code I have so far:
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int one;
System.out.print("Enter the five digit integer you would like to be split up:");
one = input.nextInt();
while (one > 0){
System.out.printf("%d%n", one % 10);
one = one /10;
}
}
First, in order to avoid printing on separate lines, you should avoid using the %n formatting character in your printf().
Now, how do you print the digits in the correct order? Well, since you are limited to five-digit numbers, you can do something like this:
for ( int divisor = 10000; divisor >= 1; divisor /= 10 ) {
System.out.printf( "%d ", n / divisor);
n %= divisor;
}
System.out.printf( "%n" ); // Just to complete the line
(divisor /= 10 is shortcut for divisor = divisor / 10, and n %= divisor is shortcut for n = n % divisor).
So you start by dividing the number by 10000. This will give you the fifth digit from the right. Then you take the remainder and put it in n. This gives you just the remaining four digits. Then the loop will reduce your divisor to 1000, which will take the fourth digit from the right, and you keep doing that until you reach a divisor of 1.
Another approach that does not require knowing that the number is 5 digits long, but requires recursion is to write a method like so:
public static void printSplitNumber( int n ) {
if ( n == 0 ) {
return;
}
printSplitNumber( n / 10 );
System.out.printf( "%d ", n % 10);
}
And from your main, call:
printSplitNumber(n);
System.out.printf("%n"); // Again, just completing the line.
This recursive method relies on the fact that you print the current digit only after all the rest of the number has been printed. So this causes it to print it to the right of the rest of the digits, giving you the effect you need.
Unless the assignment is to figure out how to split the digits numerically, I think that the simplest approach is to either use Scanner's nextLine() method to get a String, or convert your int to a String, and then split the characters of the String.
substring() is a little heavy - a lighter-weight way to do it is by inspecting character positions, like this:
public void printDigits(String chars) {
for(int i = 0; i < chars.length(); i++) {
System.out.printf("%c ", chars.charAt(i));
}
}
This approach uses the substring method as opposed to mathematically manipulating the int value.
int one;
System.out.print("Enter the five digit integer you would like to be split up:");
one = input.nextInt();
String x = Integer.toString(one);
for(int i = 0; i < x.length() - 1; i++)
{
// On last digit in number
if(i + 1 == x.length())
{
System.out.printf("%s ", x.substring(x.length()));
}
else
{
System.out.printf("%s ", x.substring(i, i + 1));
}
}
Simplified printf statemnts thanks to #Jerry101's comment