Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I had posted a question yesterday about this program I have been working on but essentially I've programmed an encoder of sorts that takes a string and an integer and then adds to every character within the string the value of the integer and then finally prints the binary of the string assuming 8 bits for every symbol or character. For example ABC with integer(code) 4 should output 01000101 01000110 01000111 (EFG). Now, I've managed to get super close to completing this project but I've run into an issue when converting each character to binary which I assume is due to how I'm actually calculating the binary.
Example: If a binary integer starts with a 0, then obviously I will need to pad the integer with a 0 on the far left. I've managed to do that but there are cases where the integer ends in 0 and I need to do the same thing except on the far right... I'm not sure if I'm making 100% sense but I have posted my code and test result with expected outcome below. As you can see, it converts almost perfectly except the value in the middle (B) adds an extra 2 zeroes instead of just one on the far left and I haven't figured out how to check to add an ending zero. Can someone please help me? How I should go ahead and handle converting to binary(8 bits) from characters?
I also need to figure out how to decode binary into the original message. Example: InputMessage: 01000101 01000110 01000111, InputCode: 4
OriginalMessage: ABC
public class Encoder{
public static void main (String[] args) {
String msg;
int code;
int i;
msg = getMsg();
code = getCode();
getBinaryMsg(getCodedMsg(msg, code));
}
public static String getMsg(){
String msg;
System.out.print("Input message: ");
Scanner input = new Scanner(System.in);
msg = input.nextLine();
return msg;
}
public static int getCode(){
int code=0;
System.out.print("Input Code from 1 - 10: ");
Scanner input = new Scanner(System.in);
return input.nextInt();
}
public static String getCodedMsg(String msg, int code){
int letterOrDigit;
String codedMessage = "";
for(int i = 0; i<= msg.length()-1; i++){
letterOrDigit = msg.charAt(i);
if(Character.isLetter(letterOrDigit)){
letterOrDigit = (char)(msg.charAt(i)+code);
}
if((Character.isLowerCase(msg.charAt(i)) && letterOrDigit > 'z') || (Character.isUpperCase(msg.charAt(i)) && letterOrDigit > 'Z')){
letterOrDigit = (char)(msg.charAt(i) - (26 - code));
}
if(Character.isDigit(letterOrDigit)){
letterOrDigit = (char)(msg.charAt(i)+code);
}
if(Character.isDigit(msg.charAt(i)) && letterOrDigit > '9'){
letterOrDigit = (char)(msg.charAt(i) - (10 - code));
}
codedMessage +=(char)letterOrDigit;
}
return codedMessage;
}
public static void getBinaryMsg(String codedMessage){
char[] strChar = codedMessage.toCharArray();
int character;
int remainder;
int binaryInt;
int revBinInt;
int firstDigit;
String paddedWithZero = "";
String binaryMsg = "";
for(int i = 0; i < strChar.length; i++){
binaryInt = 0;
revBinInt = 0;
firstDigit = 0;
character = strChar[i];
//Calculating 8 binary bits
for(int j = 0; j <= 7; j++){
remainder = character % 2;
binaryInt = binaryInt * 10 + remainder;
character = character / 2;
}
//Reversing the above for loop so that binary is correct
while(binaryInt != 0){
remainder = binaryInt % 10;
revBinInt = revBinInt * 10 + remainder;
binaryInt = binaryInt / 10;
}
firstDigit += revBinInt/(int)(Math.pow(10,(int)Math.log(revBinInt)));
if(firstDigit == 0 && numOfDigits(revBinInt) <= 7){
binaryMsg += String.format("%8s", Integer.toString(revBinInt)).replace(' ', '0') + " ";
}
}
System.out.print(binaryMsg);
}
//Counts the number of digits in case binary number starts or ends in 0
public static int numOfDigits(int number){
int count = 0;
while(number !=0){
number = number/10;
count++;
}
return count;
}
}
Test Result:
Input: ABC, 4
Output: 01000101 00100011 01000111
Expected: 01000101 01000110 01000111
As you say, you were almost done. But the binary encoding wasn't working as expected. Here is my suggestion:
public static void getBinaryMsg(String codedMessage) {
String binary = toBinary(codedMessage);
System.out.println(binary);
}
private static String toBinary(String codedMessage) {
String binary = codedMessage.chars().boxed().map(c -> pad(Integer.toBinaryString(c), 8, '0') + " ").collect(Collectors.joining());
return binary;
}
private static String pad(String s, int n, char c) {
return String.format("%"+n+"s", Integer.parseInt(s)).replace(' ', c);
}
Using Integer.toBinaryString(int i) you don't have to reinvent the wheel. The only thing you have to add is the padding, to get every binary formatted to eight bits. You did it well according to: How to get 0-padded binary representation of an integer in java?
Here's a piece of code that trims zeros on both ends of a binary string:
String s = "00010111110100";
Pattern p = Pattern.compile("(1+[01]*1+)|(1)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group());
}
It uses a regular expression (1+[01]*1+)|(1).
| in the epression means or, so it says (1+[01]*1+) or (1).
In (1+[01]*1+) 1+ means one or more repetitions of 1 and [01]* means 0 or more repetitions or 1 or 0.
(1) means just 1, to handle the case where your string looks like this: 00010000.
Edit: note that you can actually use (1[01]*1)|(1), since [01]* will handle the case of multiple 1's.
Related
I'm trying to write an algorithm which adds two numbers that are stored as chars in two arrays. Unfortunately, it doesn't work. When I try to debug it, I see that the variables a and b get the value -1 which makes no sense. Any idea what might be the problem?
public class rechner2 {
public static void main(String[] args) {
final char[] zahl1 = {1, 2, 3};
final char[] zahl2 = {7, 8, 9};
//Add arrays zahl1 and zahl2.
char [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static char[] add(char[] zahl1, char[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
char[] finalresult = new char [len + 1];
int carryover = 0;
for (int i = 0; i < len; i++) {
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = (char)c;
}
if (carryover == 1) {
finalresult[len + 1] = 1;
}
return finalresult;
}
}
in this code I believe 2 bug
instead of char , i guess better to us int
length of the array
here is the code:
public class rechner2 {
public static void main(String[] args) {
int[] zahl1 = {1,2,3};
int[] zahl2 = {7,8,9};
//Add arrays zahl1 and zahl2.
int [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static int[] add(int[] zahl1, int[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
int[] finalresult = new int [len + 1];
int carryover = 0;
for (int i = 0; i <= len-1; i++) {
int a = (zahl1[i]);
int b = (zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = c;
}
if (carryover == 1) {
finalresult[len] = 1;
}
return finalresult;
}
}
Your code is conflicted: The numbers / characters in your array are actually integers, not "printable" or "human readable" characters. But, parts of your code are treating them as if they are "printable".
Let's go back decades, and use ASCII for the beginning of this explanation. ASCII has "Printable" and "Nonprintable" characters. The "Nonprintable" characters are known as "Control codes."
Control codes include codes that move the cursor on a display terminal or print head on a printing terminal. They include thing like CR (Carriage Return), LF (Line Feed), HT (Horizontal tab), and BS (Backspace). Others are used by data communications hardware to control the flow of data, or to report status.
Printable characters correspond to what you see on a terminal screen or printout. They include uppercase alphabetic, lower case alphabetic, digits, punctuation, and the space character. They are "human readable."
Look at the list of printable characters in the Wikipedia article. Take 5 as an example. It's represented as '53' in base ten, which corresponds to '35' in base sixteen, or '011 0101' in binary. Note that it is not the same as the binary number five, which would be '0000 0101'.
Java uses 16 bit Unicode, not ASCII, for its char type. The Java compiler allows arithmetic to be done on char data, as if it was the same as short.
These lines in your code expect your char variables and constants are printable characters:
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
In addition, that you specified zwischenarray as char tells the compiler to handle the contents as printable characters in this line:
System.out.println(zwischenarray[i]);
But, the rest of your code treats your char data as integer data types.
You have a bug in this line: finalresult[len + 1] = 1;. After that bug is fixed, how do you fix the rest of your code? There are different ways, and which is best depends on your intention.
For demonstration purpose, try this: Replace the following
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
with
int c = zahl1[i] + zahl2 [i] + carryover;
Also, put a cast in your output line:
System.out.println((short)zwischenarray[i]);
And run it. That will demonstrate you can do arithmetic on Java char data.
Now, remove the (short) cast in output line, and change all occurrences of char to short (or int). Your program still works.
This is because of the way you entered the values for zahl1 and zahl2. Your source code consists of printable characters and white space. By omitting the single quotes, you told the compiler to convert the values to binary integers. For example, your source code 9 became binary 0000 1001 in the runtime code. If you wanted your 9 to remain as a printable character, you needed to enclose it in single quote marks: '9' .
By enclosing all the values in zahl1 and zahl2 in single quote marks, the use of Character.getNumericValue is appropriate. But, you would still need the (short) or (int) cast in your System.out. line to see your output.
Character.getNumericValue is returning -1 because the values passed are outside of the range it was designed to work with.
Here are two ways to convert a base 10 digit represented as a binary integer to the equivalent printable character:
finalresult[i] = (char) (c + '0');
But, my preference is for this:
final String digit = "0123456789";
finalresult[i] = digit.charAt (c);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
hi I'm using codeblocks and I'm kinda new,
I want to take apart a number and multiply its digits
and if number is > 9 then once again I want to take apart the digits and multiply them,
example: if I have the number 126 then the new number would be 1*2*6 = 12
but 12 is > 9 then once again the new number is 1*2 = 2, 2 is not >9 then get out of the loop
thanks
please try this program:
public class B {
public static void main(String[] args) {
String number = "126";
int c = 1;
for (int j = number.length() ; j >=0; j--) {
int v = j;
for (int i = 0; i < v; i++) {
String s = ""+number.charAt(i);
c = c* Integer.parseInt(s.trim());
}
System.out.println("result is : "+c);
c = 1;
}
}
}
A simple solution in C:
int muldigits(unsigned int n) {
while (n > 9) {
unsigned int m = n;
for (n = 1; m; n *= m % 10, m /= 10);
}
return n;
}
You need to use a function to work out each digit of the number you have inputted and then iterate until a zero is calculated. Something like this would work, and then just return the remainder of the switch statement:
quotient = number / 10;
remainder = number % 10;
switch(remainder)
{
case 1:
return 1
break;
}
You can create a method to find number characters in the string like below:
public static int Match(String pattern, String word) {
int abc = 1;
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(word);
while (m.find()) {
abc *= Integer.parseInt(m.group());
System.out.println("val of abc when (m=" + m.group() + ") - " + abc);
}
System.out.println("*************************");
return abc;
}
Then you can check the given String inside your main method until you get the required number:
String word = "126 Florida Beach";
String pattern = "\\d";
int abc = 1;
do {
System.out.println("word at - " + word);
System.out.println("abc at - " + abc);
abc = Match(pattern, word);
word = String.valueOf(abc);
} while (abc > 9);
System.out.println("Required Value - " + abc);
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 7 years ago.
Below is a code that I have for flipping a given integer and displaying the flipped results. It runs but I have issues for when the number is smaller than two digits. It obviously cannot be flipped. I wanted to make the loop an if else stating "if number is two digits or more reverse." "Else state that the integer needs to be two or more digits." how could I go about this?
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer that you would like to have reversed: ");
int number = input.nextInt();
reverse(number);
}
public static void reverse(int userInteger)
{
int tempDigit = 0;
while (userInteger > 0){
tempDigit = userInteger % 10;
System.out.print(tempDigit);
userInteger = userInteger / 10;
}
}
}
I am trying to get it to understand that 01 can be converted to 10. This would need to be done by the code understanding that the userInteger is more than one digit but I cant seem to figure out how to do that... Any ideas on how I can get this to check for two digits and execute the loop accordingly would be appreciated!
public static void reverse(int n)
{
int temp = 0;
int count = 0;
while(n != 0)
{
if(n%10 == 0)count++;
temp = temp*10 + n %10;
n /= 10;
}
for(int i = 0; i < count; i++)
{
System.out.print(0);
}
System.out.println(temp);
}
Convert the int to a String using Integer.toString method and save it to a string. Declare a String that will be later used as output. Start a for loop that goes through the number ( which was converted to a String) from its end to its beginning. It add each character from end to start to the output String. This results in the output String to be the reverse of the number String. Then just simply convert the output String using Integer.parseInt method and return the int value.
The code should look like:
public static int reverse(int n)
{
String number = Integer.toString(n);
String output;
for(int i = number.length()-1; i >= 0; i--)
output += number.charAt(i);
return Integer.parseInt(output);
}
I recommend using String.valueof(int).toCharArray(); and looping through in reverse to compose a new char[]. Then use Integer.parseInt(String);
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
I have numeric input (11 digits), and I need to perform some operations on each digit (example: multiply 1st by 5, 2nd by 3, etc.). How can I do so in Java? Is there a simple way to access single letter / digit? Is there another way to do it?
If you don't want to convert the number to a string, then there is a simple trick.
digit = number % 10
will give you the right most digit.
number = number / 10
Will remove the right most digit from the number.
So you can run in a loop until the number reaches 0.
while(0 < number)
{
int digit = number % 10;
number = number / 10;
// do here an operation on the digits
}
You can use a for loop to help you count. For example
for(int index = 0; 0 < number; ++index, number /= 10)
{
int digit = number % 10;
// do an operation on the number according to the 'index' variable
}
Here is a similar StackOverFlow question on a similar question
Well there are many ways you can do it like :
int a = 12345;
int b;
while(a>0)
{
b = a%10;
System.out.print(b + " ");
a = a/10;
}
Here it gives you the digits in reverse order like you will get b=5 then b=4....
You can just manipulate them
Other way
int d = 12345;
String str = String.valueOf(d);
for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
System.out.print(Character.getNumericValue(c) * 10 + " ");
}
Or
char c[] = str.toCharArray();
for(Character ch : c)
{
System.out.print(Character.getNumericValue(ch) * 2 + " ");
}
You can use .charAt() to get a character from a string. Then using Character.getNumericValue() you can convert the character to an integer.
Like this:
String string = "1434347633";
int digit1 = Character.getNumericValue(string.charAt(1));
Convert that number input to String data type so that you can interpret it as a String.
int numbers = 1122334455; // integer won't be able to save this much data,
// just for example ok,
String numberString = numbers.toString();
foreach (char number in numberString) {
// do work on each of the single character in the string.
}
You should work them out, depending on the some condition.
If you want to access the digits by index without converting to a string, you can use these two functions length and digitAt:
public class DigitAt {
public static int length(long v) {
return (int) Math.ceil(Math.log10(v));
}
public static int digitAt(long v, int digit) {
return (int) ((v / (long) Math.pow(10, length(v) - digit - 1)) % 10);
}
public static void main(String[] args) {
System.out.println("Digits: " + length(1234567));
System.out.println(digitAt(1234567, 0));
System.out.println(digitAt(1234567, 1));
System.out.println(digitAt(1234567, 6));
}
}
public String stringAfterOperations(String digits) {
ArrayList<Integer> z = new ArrayList<Integer>();
for(Character c: digits.toCharArray()) {
z.add(Character.getNumericValue(c));
}
//TODO Set your own operations inside this "for"
for(int i=0; i<z.size(); i++){
if(i == 1){
z.set(i, z.get(i)*4);
}
else if(i == 7){
z.set(i, z.get(i)/3);
}
else {
z.set(i, z.get(i)+2);
}
}
String newString = "";
for(Integer i: z){
newString += i;
}
return newString;
}