How to concatenate seperate digits from a loop into one single integer - java

okay so I have an assignment that says i have a string of numbers for example
"1234 4014 5555 7654" say which is essentially a credit card number.
They are asking me to convert the string of digits into single integers then concatenate them into 4 lots of 4 digit integers so the string "1234 4014 555 7654" for example will have 4 blocks
block 1 would be 1234
which is converted into 1, 2, 3, 4
which is then concatenated into 1234 as an integer
i have to do this for all the blocks... :(
So far.. i made a for loop as shown below :
public static int toInt(String digitString)
{
int answer = 0;
int num = 0;
for (int j = 0; j < digitString.length(); j++){
num = (int) digitString.charAt(j) - '0';
System.out.println(num);
}
return answer
}
and i can successfully convert the string into seperate digits but i have no idea how i can concatenate those digits into 4, 4 digit integers
any help would be much appreciated :)

I'm not going to do your assignment for you, but I'll tell you this hint: All you need to know to understand and solve this problem is that Integer.parseInt(s) for some String s returns s as an integer, and that s.substring(n, n+1) returns the (n+1)st character of a String.
For example
String s = "1234";
s = s.substring(0, 1); //s = "1"
int val = Integer.parseInt(s); //val = 1
And that's it. Now it's just a matter of looping over your String and doing whatever you want with them. I suppose it might be helpful to know that you can assign an integer to a string with:
String temp = val + "";
//or
String temp = String.valueOf(val);

Related

Take in String that contains number characters and add commas to each thousands place WITHOUT converting string into int or long

I want to take in a string for example "1234567890" and add commas to each thousands place in the number. However, I don't want to parse this string into an int or long. I think I might need to use recursion but I dont know how.
String number1 = "1234567890";
System.out.println(stringNumberAddCommas(number1));
//output == 1,234,567,890
public static String stringNumberAddCommas(String number1){ }
we can achieve this as below as well-
public static String stringNumberAddCommas(String number) {
for (int i = number.length() - 1; i >= 0; ) {
if (i >= 3) {
number = number.substring(0, i - 2) + "," + number.substring(i - 2);
}
i = i - 3;
}
System.out.println("number=" + number);
return number;
}
There's no need to mess with recursion; all you need is to realize that you need to either work backwards or do some very basic math based on length.
Given a pile o digits that is, say, 8 characters long, that's all the information you need to know that the first comma is after 2 digits, and then every further comma at +3 digits from that position until you reach the end.
Tools needed:
"12345678".length() (= 8)
"12345678".substring(2, 5) (= "345")
a for (int i = ...; i < in.length(); i+= 3) loop.
a new StringBuilder() along with its .append() method, both for appending the comma as well as those substrings.
Some exceedingly basic math on that length, involving in particular the % operator. a % b divides a by b, tosses the result in the garbage, and returns the leftovers. In other words, 5 % 3 returns 2 (because 5 divides into 3 one time, and that leaves a remainder of 2).
String test = "1234567890";
String reversed = new StringBuffer(test).reverse().toString();
int i = 0;
StringBuilder ans = new StringBuilder();
while(i+3<reversed.length()){
ans.append(reversed, i, i + 3).append(",");
i+=3;
}
ans.append(reversed, i, reversed.length());
String solution = ans.reverse().toString();
I'd define an offset to find the length of the first substring, then iterate over the string in 3 character substrings.
StringJoiner would also be helpful in adding the needed commas.
public static String stringNumberAddCommas(String str){
int offset = str.length() % 3 != 0 ? str.length() % 3 : 3;
StringJoiner sj = new StringJoiner(",");
for (int s = 0, i = offset; i <= str.length(); s = i, i += 3) {
sj.add(str.substring(s, i));
}
return sj.toString();
}

Extract the last 2 digits of an integer (Java)

I have some code that takes an integer and extracts the last 2 numbers and prints them. For example, if I input 10000001, 01 should be the printout/ output. The problem here is that for some reason the output of the program is 1. I am not sure why the output shows up as a single digit.
public class Main {
public static void main(String[] args) {
double num = 10000001;
double digit = num % 100;
System.out.println(digit);
}
}
Your problem is simple and has a simple answer.
In java int num = 1; is same as int num = 01; (both mean same 1 for the compiler) so when you are using % 100 with your number it returns 01 which is nothing but 1 for java as you are storing it to a double data type variable (actually when you use double in this line double digit = num % 100; it prints 1.0 , so you should use int here int digit = num % 100; to remove the decimal point).
So using int digit = num % 100; will work and give you desired results with all number except numbers having a 0 before a number.
To solve your problem completely you can use String class.
String str = num+""; //connverting int to string
String digit = str.substring(str.length()-2, str.length());
This is because your calculated value is "01". which while display java is considering it as "1". You can use padding but have to convert that integer to a string.
public static void main(String []args){
double num = 10000001;
int digit =(int) num%100;
String padding =String.format("%02d",digit);
System.out.println(padding);
}
Or If you are taking binary numbers better to use string and then displaying last two numbers using length() on string.
Another method you can try out is extracting the last two digits and printing as string.
int num = 10001;
int last_digit = num % 10; // extract the last digit
num /= 10; // modify the original number
int second_to_last_digit = num % 10; // extract second last digit
String str = String.valueOf(second_to_last_digit) + String.valueOf(last_digit); // convert and add strings
System.out.println(str); // print desired string

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

Output for Converting a number in decimal into its Complement

Output for converting a number in decimal into its 1s complement and then again converting the number into decimal does not come as expected.
MyApproach
I first converted the number from decimal to binary. Replaced all Os with 1 and vice versa and then converted the number into decimal.
Can anyone guide me? What I am doing wrong?
Code:
public static int complimentDecimal(int num) {
int p = 0;
String s1 = "";
// Convert Decimal to Binary
while (num > 0) {
p = num % 2;
s1 = p + s1;
num = num / 2;
}
System.out.println(s1);
// Replace the 0s with 1s and 1s with 0s
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(j) == 0) {
s1.replace(s1.charAt(j), '1');
} else {
s1.replace(s1.charAt(j), '0');
}
}
System.out.println(s1);
int decimal = 0;
int k = 0;
for (int m = s1.length() - 1; m >= 0; m--) {
decimal += (s1.charAt(m) * Math.pow(2, k));
k++;
}
return decimal;
}
First of all you need to define the amount of Bits your binary representation should have or an complement representation does not make sense.
If you convert 100 the binary is 1100100
complement is 0011011 which is 27
now convert 27. Binary is 11011, complement 00100 which is 4.
Now define yourself a Bit length of 8.
100 is 01100100, complement 10011011, is 155
155 is 10011011, complement 01100100, is 100
Works because every binary representation has a length of 8 bits. This is absolutly necessary for the whole complement thing to make any sense.
Consider that you now have a limit for numbers that are convertable.
11111111 which is 255.
Now that we talked about that I will correct your code
static int MAX_BITS = 8;
static int MAX_INT = (int)Math.pow(2, MAX_BITS) - 1;
public static int complimentDecimal(int num)
{
// check if number is to high for the bitmask
if(num > MAX_INT){
System.out.println("Number=" + num + " to high for MAX_BITS="+MAX_BITS);
return -1;
}
// Your conversion works!
int p=0;
String s1="";
//Convert Decimal to Binary
while(num>0)
{
p=num%2;
s1=p+s1;
num=num/2;
}
// fill starting zeros to match MAX_BITS length
while(s1.length() < MAX_BITS)
s1 = "0" + s1;
System.out.println(s1);
//Replace the 0s with 1s and 1s with 0s
// your approach on that is very wrong
StringBuilder sb = new StringBuilder();
for(int j=0;j<s1.length();j++){
if(s1.charAt(j)=='0') sb.append("1");
else if(s1.charAt(j)=='1') sb.append("0");
}
s1 = sb.toString();
/*
for(int j=0;j<s1.length();j++)
{
if(s1.charAt(j)==0)
{
s1.replace(s1.charAt(j),'1');
}
else
{
s1.replace(s1.charAt(j),'0');
}
}
*/
System.out.println(s1);
int decimal=0;
int k=0;
for(int m=s1.length()-1;m>=0;m--)
{
// you don't want the char code here but the int value of the char code
//decimal += (s1.charAt(m) * Math.pow(2, k));
decimal+=(Character.getNumericValue(s1.charAt(m))*Math.pow(2, k));
k++;
}
return decimal;
}
Additional Note: Don't get bigger then MAX_BITS = 31 or you need to work with long instead of int in your method.
First of all you have to assign the replaced String to the already defined variable that is,
s1.replace(s1.charAt(j),'1');
it should be
s1 = s1.replace(s1.charAt(j),'1');
and the next case is, when you are changing in that order it would change all the characters similar to matched case
refer Replace a character at a specific index in a string?
String.Replace(oldChar, newChar) method returns a new string resulting from replacing all occurrences of oldChar in given string with newChar. It does not perform change on the given string.
The problem (OK, one of the problems) is here:
if(s1.charAt(j)==0)
Characters in Java are actually integers, in the range 0 to 65535. Each of those numbers actually means the character corresponding to that number in the Unicode chart. The character '0' has the value 48, not 0. So when you've created a string of '0' and '1' characters, the characters will have the integer values 48 and 49. Naturally, when you compare this to the integer 0, you'll get false no matter what.
Try
if(s1.charAt(j)=='0')
(Note: OK, the other answer is right--replace does not work. Not only are you using it incorrectly, by not assigning the result, it's not the right method anyway, because s1.replace(s1.charAt(j),'1') replaces all '0' with '1' characters; it doesn't replace character j. If you specifically want to replace the j'th character in a String with something else, you'll need to use substring() and build a new string, not replace().)
A couple other things to note: (1) Integers are not "decimal" or "binary". When your method gets the num parameter, this is just a number, not a decimal number or a binary number. It's represented in your computer as a binary number (unless you're using something like a Burroughs 3500, but I think all of those died before Java was invented). But it really isn't considered decimal, binary, octal, hex, ternary, or whatever, until you do something that converts it to a String. (2) I know you said not to post alternative approaches, but you could replace the entire method with just one line: return ~num;. That complements all the bits. If you were thinking that you couldn't do this because num was a decimal number, see #1. (3) "Compliment" means to say something nice about somebody. If you're talking about flipping all the bits, the correct spelling is "complement".

Retrieving the first digit of a number [duplicate]

This question already has answers here:
Return first digit of an integer
(25 answers)
Closed 5 years ago.
I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.
int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????
Almost certainly more efficient than using Strings:
int firstDigit(int x) {
while (x > 9) {
x /= 10;
}
return x;
}
(Works only for nonnegative integers.)
int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
firstDigit = number/((int)(pow(10,(int)log(number))));
This should get your first digit using math instead of strings.
In your example log(543) = 2.73 which casted to an int is 2.
pow(10, 2) = 100
543/100 = 5.43 but since it's an int it gets truncated to 5
int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Integer.parseInt will take a string and return a int.
This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.
private static int getMostSignificantDigit(double value) {
value = Math.abs(value);
if (value == 0) return 0;
while (value < 1) value *= 10;
char firstChar = String.valueOf(value).charAt(0);
return Integer.parseInt(firstChar + "");
}
To get the first digit, this sticks with String manipulation as it is far easier to read.
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}

Categories