for Example:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26
but i does not get desired results
when i add all char it gives
output as:
266
import java.util.Scanner;
public class ProjectEu {
public static void main(String...rDX) {
int degree = new Scanner(System.in).nextInt();
String store = Integer.toString((int)Math.pow(2,degree));
char [] finals = store.toCharArray();
int temp = 0;
for (int i = 0, n = store.length(); i < n; i++) {
System.out.printf("values[%d] --> %c \n",i, finals[i]);
temp = temp + finals[i];
}
System.out.println(temp);
}
}
The reason that you are getting this error is because temp is an integer, but finals[i] is a character, so it converts the characters into ASCII values and adds them. You can fix this problem by doing:
for (int i = 0, n = store.length(); i < n; i++) {
char ch = store.charAt(i);
int digit = Integer.parseInt(Character.toString(ch));
temp = temp + digits;
}
Try this:
int sum = store.chars()
.boxed()
.map(Character::getNumericValue)
.mapToInt(Integer::intValue)
.sum();
This line:
temp = temp + finals[i];
sums temp and the ASCII code of the char stored in finals[i].
You can get the value of the digit by this:
temp = temp + finals[i] - '0';
This means that by subtracting from the digit's ASCII code the ASCII code of 0 you get the number value of the digit.
When you are adding a character to an integer, you are adding the integer code of the character, not its actual numeric value .
What you need is Character.getNumericValue :
temp = temp + Character.getNumericValue(finals[i]);
Related
I am currently a beginner in programming and I am trying to write a program in java to convert binary in hexadecimal numbers.
I know that the program will have to divide the number in groups of 4 and convert them to hexadecimal.
Ex: 11101111 (b2) --> E + F --- EF
However, since I used ints to do the conversion of the numbers, I'm stuck when I need to print a letter because it is a String.
Can someone point me to the right way? What am I doing wrong? I've also tried another version with an auxiliary array to store each group of 4 digits but I can't manage to insert a proper dimension to the array.
Unfortunately I am not allowed to use any function other than Scanner and Math, the method lenght and charAt and the basic stuff. I can't modify the public static line either.
EDIT: So after your inputs and so many tries, I managed to get this code. However it gives me an error if I insert too many numbers, eg: 0111011010101111. I've tried to change int to double but that didn't fix the problem.
import java.util.Scanner;
public class Bin2HexString {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.println("Valor?");
int vlr = keyb.nextInt();
String num = "";
int aux = vlr;
// Hexadecimal numbers
String arr[] = {"0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D", "E", "F"};
String bits[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String letters = "";
//Divide in groups of 4
int r;
for (; aux > 0; ) {
r = aux % 10000;
aux = aux / 10000;
num = "" + r;
for (;num.length() < 4;) { //add missing zeros
String zero = "0";
num = zero + num;
}
int charint = 0,bitint = 0;
for (int i = 0; i < arr.length;i++) {
String aux2 = bits[i];
String aux3 = arr[i];
for (int j = 0; j < num.length();j++) { // compare each group with arr[i]
char charvl = num.charAt(j);
char bitsvl = aux2.charAt(j);
charint = ((int) (charvl)-'0');
bitint = ((int) (bitsvl) - '0');
if (bitint != charint)
break;
}
if (bitint == charint)
letters = aux3 + "" + letters;
}
}
System.out.println(letters);
}
}
Having thought about this for a while to determine the most effective and useful way to do this is to write methods which convert a string from any base between 2 and 16 to an int and back to a string again.
This way you have useful methods for other things. And note that they methods can be easily changed and names to simply hard code the desired radix into the method to limit it to binary and hex methods.
The indexOf utility method was written to avoid using the builtin String method.
final static String hex = "0123456789ABCDEF";
static int stringToInt(String str, int radix) {
if (radix < 2 || radix > 16) {
System.out.println("Base must be between 2 and 16 inclusive");
return -1;
}
int v = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int idx = indexOf(hex, c);
if (idx < 0 || idx > radix) {
System.out.println("Illegal character in string (" + c + ")");
}
v = v * radix + idx;
}
return v;
}
static String intToBase(int v, int radix) {
if (radix < 2 || radix > 16) {
System.out.println("Base must be between 2 and 16 inclusive");
return null;
}
String s = "";
while (v > 0) {
int idx = v % radix;
s = hex.charAt(idx) + s;
v /= radix;
}
return s;
}
static int indexOf(String str, char c) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
return i;
}
}
return -1;
}
And here is an example of their use.
// generate some test data
Random r = new Random(23);
String[] bitStrings =
r.ints(20, 20, 4000).mapToObj(Integer::toBinaryString).toArray(
String[]::new);
for (String bitstr : bitStrings) {
int v = baseToInt(bitstr, 2);
String hex = intToBase(v, 16);
System.out.printf("%12s = %s%n", bitstr, hex);
}
Which prints the following:
101110000011 = B83
111001111100 = E7C
10001110111 = 477
100110001111 = 98F
111001010 = 1CA
111001001111 = E4F
111000011010 = E1A
100001010010 = 852
11011001101 = 6CD
111010010111 = E97
Just some quick notes:
First this is wrong:
//Divide in groups of 4
for (; aux > 0; ) {
r = aux % 10000;
aux = aux / 10000;
Not at all what you want to do. Try it by hand and see what happens. Take a simple number that you know the answer to, and try it. You won't get the right answer. A good test is 17, which is 11 hex.
Try this instead: convert directly to the base you want. Hex is base 16 (its radix is 16), so you use 16 instead.
//Divide in groups of 4
for (; aux > 0; ) {
r = aux % 16;
aux = aux / 16;
Try those numbers with the test case, which is 17, and see what you get. That will get you much closer.
I'm assuming by "without methods" in the title, you are attempting to write your own integer parsing method instead of using Scanner.nextInt(int radix). In that case, my first advice would be work with a string instead of an integer - you'll be able to handle larger numbers and you can simply make an array of substrings (length 4) to convert to letters.
So, if you use the string approach - first scan in a string, not an int. Then I'd recommend a hash table with the 4-bit strings as keys and the hexadecimal equivalents as values. That should make calculation quite fast.
e.g.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapBin2Hex
{
public static void main(String[] args)
{
//Read the string in
Scanner sc = new Scanner(System.in);
System.out.println("Binary number?");
String bin = sc.nextLine();
//Pad the bitstring with leading zeros to make a multiple of four
String zeros = "";
int i;
if (bin.length() % 4 != 0)
{
for (i = 0; i < 4 - (bin.length() % 4); i++)
{
zeros += "0";
}
}
bin = zeros + bin;
//Split the padded string into 4-bit chunks
String[] chunks = new String[bin.length() / 4];
for (i = 0; (i * 4) < bin.length() - 1; i++)
{
chunks[i] = bin.substring(i * 4, (i * 4) + 4);
}
//Convert the chunks to hexadecimal
String hex = "";
Map<String, String> bin2hex = new HashMap<>();
bin2hex.put("0000", "0");
bin2hex.put("0001", "1");
bin2hex.put("0010", "2");
bin2hex.put("0011", "3");
bin2hex.put("0100", "4");
bin2hex.put("0101", "5");
bin2hex.put("0110", "6");
bin2hex.put("0111", "7");
bin2hex.put("1000", "8");
bin2hex.put("1001", "9");
bin2hex.put("1010", "A");
bin2hex.put("1011", "B");
bin2hex.put("1100", "C");
bin2hex.put("1101", "D");
bin2hex.put("1110", "E");
bin2hex.put("1111", "F");
for (String s : chunks)
{
hex += bin2hex.get(s);
}
System.out.println("Hexadecimal: " + hex);
sc.close();
}
}
Further iterations could have some error checking to prevent catastrophic failure in the case of characters other than 0 or 1.
And of course, if you're fine with the other way (builtins), the following is far easier and more robust (ie will throw an exception if the string contains anything other than 0s and 1s):
import java.util.Scanner;
public class BuiltinBin2Hex
{
public static void main(String[] args)
{
//Read the binary number in
Scanner sc = new Scanner(System.in);
System.out.println("Binary number?");
int bin = sc.nextInt(2);
//And print as hexadecimal
System.out.println("Hexadecimal: " + Integer.toString(bin, 16));
sc.close();
}
}
I need to write code for removing the first digit if an int is more than 3 digits. For example if I have 1055 then the output would be 055. My current code removes the first digit but the problem is it also removes the zeros and outputs 55 instead of 055. How would I got about to fix this? The variable that I'm referring to is the checksum
int checksum = 0;
int l = message.length();
for (int i = 0; i < l; i++) { 3
checksum += message.charAt(i);
}
if (checksum >= 1000) {
checksum = Integer.parseInt(Integer.toString(checksum).substring(1));
}
physicalLayer.sendFrame("(" + message + ":" + checksum + ":.)");
You obviously cannot keep leading zeros in int data type.
So, keep the result in a String copy
int checksum=0;
int l= message.length();
for (int i = 0; i < l; i++) {
checksum+= message.charAt(i);
}
String sChecksum = Integer.toString(checksum);
if(checksum>=1000){
sChecksum= sChecksum.substring(1);
}
physicalLayer.sendFrame("("+message+":"+sChecksum+":.)");
You mention if the it is more than 4 digits then
int number = 1055;
String text_no = Integer.toString(number);
//System.out.println(text_no.substring(1,3));
if(text_no.length() > 4) {
System.out.println(text_no.substring(1));
}
But "1055" has only 4 digit then if condition does not work if you need to check only 4 digit and more that for digits then this will work
int number = 1055;
String text_no = Integer.toString(number);
//System.out.println(text_no.substring(1,3));
if(text_no.length() >= 4) {
System.out.println(text_no.substring(1));
}
Is there any good way to search through a floats first four numbers and return every number separately with int[]?
Example: the float 23,51 becomes the integer array, array[0]=2, array[1]=3, array[2]=5 and last array[3]=1
My code:
public void printNumber(float number){
String string = String.valueOf(number);
while(!numbers.isEmpty()){
numbers.remove(0);
}
for(int i = 0; i < string.length(); i++) {
int j = Character.digit(string.charAt(i), 10);
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
I should mention that Number is a class that only returns a different picture based on the number the constructor is given and ofcourse the number itself.
numbers is an ArrayList
Convert float to String using fixed-point format, then go through its characters one-by-one, and ignore the decimal point.
If the number could also be negative, you need to pay attention to the sign in the String output:
float v = 23.51F;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
char[] d = df.format(v).toCharArray();
int count = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
count++;
}
}
int[] res = new int[count];
int pos = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
res[pos++] = Character.digit(d[i], 10);
}
}
Demo.
Important: Be aware that floats are inherently imprecise, so you may get a "stray" digit or two. For example, your example produces
[2 3 5 1 0 0 0 0 2 3]
with 2 and 3 at the end.
You can convert the float to String with 4 decimal places using String.format method, and then get each character to int array
float floatValue = 12.34567f;
String str = String.format("%.4f", floatValue);
// remove the minus, dot, or comma (used in some countries)
str = str.replaceAll("[-|.|,]", "");
int [] nums = new int[str.length()];
for (int i=0; i<str.length(); i++) {
nums [i] = str.charAt(i) - '0';
}
Here is DEMO
As for the code last line, decimal value of '0' char (which is 48) is subtracted from a decimal value of digit char, and the result is integer value of that digit (as specified in below table):
Java 8 flavored solution:
float number = -7.54f;
int[] digits = String.format("%.3f", number)
.chars()
.filter(Character::isDigit)
.limit(4L)
.map(Character::getNumericValue)
.toArray();
System.out.println(Arrays.toString(digits)); //=> [7, 5, 4, 0]
Use the static method Float.toString() to convert your float to a String.
Then go through each char and use Integer.parseInt() to get back to an int.
public void printNumber(float number){
String string = Float.toString(number);
for(int i = 0; i < string.length(); i++) {
int j = Integer.parseInt(string.charAt(i));
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
Another option
public static void main(String[] args) {
float number = 23.51f;
String strNumber = String.valueOf(number).replaceAll("\\D", "");
int[] arrNumber = new int[strNumber.length()];
for (int pos = 0; pos < strNumber.length(); ++pos) {
arrNumber[pos] = Integer.valueOf(String.valueOf(strNumber.charAt(pos)));
System.out.println(arrNumber[pos]);
}
}
I have to create a program that uses Luhn's algorithm to check to see if a credit card is valid.
The algorithm is this:
Form a sum of every other digit, including the right-most digit; so
5490123456789128 sums to 8+1+8+6+4+2+0+4 = 33
Form double each remaining digit, then sum all the digits that creates it; the remaining digits in our example (5 9 1 3 5 7 9 2) double to 10 18 2 6 10 14 18 4, which sums to 1+0+1+8+2+6+1+0+1+4+1+8+4 = 37
Add the two sums above (33+37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number.
I made a Scanner and saved the credit card number into String card number
Then I created a while loop to save every other character starting from the right into a string. So now, I have a string filled with every other digit of the credit card number, starting from the right. However, I need to add up all of the digits within that string, which I can't figure out.
For example, if the user entered 1234 as the card number, the string everyotherdigit = 42. How can I add up 4 and 2 within the string?
There are numerous ways to do that. You can actually find your own solution by doing a bit of googling.
Anyway, this is what you can do:
Get individual characters from your string, and convert them to int.
String cardNumber = "5490123456789128";
int value = cardNumber.charAt(0) - '0';
Using a for loop and changing 0 to x(loop counter) will solve everything.
Get single String and convert to int.
String cardNumber = "5490123456789128";
int value = Integer.parseInt(cardNumber.substring(0,1));
I'd treat the string as an array of chars, and use Character.digit(int, int) to convert each character to the corresponsing int:
public static boolean isValidCreditCard (String s);
char[] arr = s.toCharArray();
int everyOtherSum = 0;
for (int i = arr.length - 1; i >= 0; i -= 2) {
everyOtherSum += Character.digit(arr[i], 10);
}
int doubleSum = 0;
for (for (int i = arr.length - 2; i >= 0; i -= 2) {
int currDigit = Character.digit(arr[i], 10);
int doubleDigit = currDigit * 2;
while (doubleDigit > 0) {
doubleSum += (doubleDigit % 10);
doubleDigit /= 10;
}
}
int total = everyOtherSum + doubleSum;
return total % 10 == 0;
}
So something like this would work for you:
public static void main(String[] args)
{
String cardNum = "5490123456789128";
String others = null;
int evenDigitSum = 0;
int oddDigitTransformSum = 0;
for (int pos = 0; pos < cardNum.length(); pos++)
{
if ((pos%2) != 0)
{
evenDigitSum += (cardNum.charAt(pos) - '0');
}
else
{
others = Integer.toString((cardNum.charAt(pos)-'0')*2);
for (char c : others.toCharArray())
{
oddDigitTransformSum += (c-'0');
}
}
}
System.out.println("Odds: " + oddDigitTransformSum);
System.out.println("Evens: " + evenDigitSum);
System.out.println("Total: " + (evenDigitSum+oddDigitTransformSum));
System.out.println("Valid Card: " + ((evenDigitSum+oddDigitTransformSum)%10==0));
}
public int cardCount(String numbers){
Stack<Integer> stack = new Stack<>();
int count = 0;
for(char c : numbers.toCharArray()){
stack.push(Character.getNumericValue(c));
}
int size = stack.size();
for(int i=1;i <= size; i++){
if(i%2 != 0){
count = count + stack.pop();
}else{
stack.pop();
}
}
return count;
}
This just does what you asked, not the entire algorithm
So if I have an inputted integer:
int num_1 = 128
How would I be able to parse through the number and obtain a 1, 2 and 8, and assign them to different variables?
Thanks!
the inefficient way to do this would be to convert the integer to a string and iterate on the string characters.
the more efficient way would be something like:
int n = 128;
while (n > 0) {
int d = n / 10;
int k = n - d * 10;
n = d;
System.out.println(k);
}
The answer that Thilo wrote is good but incomplete, you start by doing:
char[] digitsAsChars = String.valueOf(num_1).toCharArray();
and then:
int[] digits = new int[charNums.length];
for(int i=0; i<charNums.length; i++){
digits[i] = charNums[i]-48;//convert char to int
}
now digits holds the digits of the number as an int array
try
while (num_1> 0){
int digit = num_1%10;
num_1 = num_1/10;
System.out.println(digit);
}
int num = 128;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.println("digit: " + j);
}
Output:
digit: 1
digit: 2
digit: 8
Turn it into a String and go character by character for the digits:
char[] digits = String.valueOf(num_1).toCharArray();
Here's one way:
String digits = Integer.toString(num_1);
int digit1 = Character.digit(digits.charAt(0), 10);
int digit2 = Character.digit(digits.charAt(1), 10);
int digit3 = Character.digit(digits.charAt(2), 10);
Of course, if the integer has more than three digits, using a loop would be more practical:
String sDigits = Integer.toString(num_1);
char[] cDigits = sDigits.toCharArray();
int[] digits = new int[cDigits.length];
for (int i = 0; i < cDigits.length; i++)
digits[i] = Character.digit(cDigits[i], 10);
With the above code in place, it's easy to extract the digits from the array:
int digit1 = digits[0];
int digit2 = digits[1];
int digit3 = digits[2];
Collect all the digits in the Array and use futher
import java.lang.Integer;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class Test
{
public static void main(String[] args) {
Integer num = 12345;
Integer[] digits = getDigits(num.toString());
System.out.println(Arrays.toString(digits));
}
public static Integer[] getDigits(String number) {
List<Integer> digits = new ArrayList<Integer>();
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
digits.add(j);
}
return digits.toArray(new Integer[]{});
}
}
Output should be
[1, 2, 3, 4, 5]
Here is a purely mathematical way of doing so:
// Returns digit at pos
static int digitAt(int input, int pos){
int i =(int) (input%(Math.pow(10, pos)));
int j = (int) (i/Math.pow(10, pos-1));
return Math.abs(j); // abs handles negative input
}
For example if input = 1234 and pos = 2, then i is 34. We divide the 34 by 10 and round off to get a 3.
Not that pretty, but works!
String str = Integer.toString(num_1);
You can obtain 1,2,8 from this str
This code returns the nibble at the given index. If you want to get all digits, you can call this method with all indices of your number. It does not work on the hexadecimal representation of a number but on the decimal one.
public static int getNibble(int number, int nibbleIndex)
{
int nibble = 0;
while (nibbleIndex >= 0)
{
int division = number / 10;
nibble = number - division * 10;
number = division;
nibbleIndex--;
}
return nibble;
}
Now if you are trying to single out numbers in a string among letters then this should take care of that.
String string = "Th1s 1s n0t a number";
int newNum = Integer.parseInt(string.replaceAll("[\\D]", ""));
return newNum;
This should return 110
Also, here is a link to a stack discussion that I found really helpful.
Get int from String, also containing letters, in Java
If you don't appreciate the idea of String conversion and want to iterate using normal order, try this:
int n = 123456789;
int digits = (int) Math.log10(n);
for (int i = (int) Math.pow(10, digits); i > 0; i /= 10) {
System.out.println(n / i);
n %= i;
}
Output would be
1
2
3
4
5
6
7
8
9
To know where the digits are coming from I'd go:
return (x/10/10) + (x%10) + (x/10)%10;
I think you can use this solution :
int getDigit(int num,int location){
return BigDecimal.valueOf(num/Math.pow(10,position)).intValue() %10;
}
in this solution what will happen is the following you are sending a number due to usage of Math that returns a double we need to convet it again to integer we use the BigDecimal.
the main idea or logic is the Math.pow with the position it returns the prefix of number and then the module chops the other end.
you can check it with the following Sample:
System.out.println(getDigit(123456,1));
System.out.println(getDigit(123456,2));
System.out.println(getDigit(123456,3));
System.out.println(getDigit(123456,4));
System.out.println(getDigit(123456,5));
System.out.println(getDigit(123456,10) );
Enjoy
Java 8 Solution
String.valueOf(n).chars().forEach(i -> System.out.println((char) i))
where n=the integer