This question already has answers here:
Extracting digits of int in Java
(15 answers)
Closed 6 years ago.
So I'm in a process of writing a small encrypter program. I start by asking the user to enter a 4 digit number (>= 1000 and <= 9999). I'd like to extract each digit from the number entered by the user, and store them in a variable.
My assignment gives me hint which doesn't help me much (Hint: integer division and the modulus might be useful here).
The "hint" is actually a nearly direct explanation of how to do what you need to do: dividing in integers by ten gets rid of the last digit, while obtaining modulo ten gives you the last digit:
int x = 12345;
int lastDigit = x % 10; // This is 5
int remainingNumber = x / 10; // This is 1234
Do this in a loop until the remaining number is zero. This gives you digits of the number in reverse.
You can use Integer.toString(int) and then address each digit by index.
int x = 1234;
char[] s = Integer.toString(x).toCharArray();
System.out.println(s[0]);
System.out.println(s[1]);
System.out.println(s[2]);
System.out.println(s[3]);
If you don't want to convert your string to an array you can use the .charAt(int n) method on the string.
int x = 1234;
String s = Integer.toString(x);
System.out.println(s.charAt(0));
Related
This is the question.
An alien spaceship broadcasts a frequency of digital signals that can be
converted into 0-1 digits (always a 8 digit combination). In brief, a stream of digits entered via the console is supposed to be caught. It is obvious that the digits we acquire can be converted into base ten - decimal. The situation here is the noise which interferes with the original signal that we are listening to. Signal noise, which negates the last item of the stream, may appear in the very first character of your input stream. All of the characters must be either 0 or 1, otherwise it is a noise. Every first character is always 0. The input stream will be taken as a single set of numeric characters.
I changed too many thing in code and still it is not working with all numbers. But I got the message from these codes:
01000110
21010011
21001000
01000101
01001110
51000101
when we converted these to correct version it'll give the message. For example these give "FRIEND". I found this but program is not working with 00000000. It gives error. How can I correct this.
Scanner inp = new Scanner(System.in);
int frequency = inp.nextInt();
int digit1 = frequency/10000000;
int digit2 = (frequency/1000000)%10;
int digit3 = (frequency/100000)%10;
int digit4 = (frequency/10000)%10;
int digit5 = (frequency/1000)%10;
int digit6 = (frequency/100)%10;
int digit7 = (frequency/10)%10;
int digit8 = frequency%10;
int decimal_version = digit1*10000000 + digit2*1000000 + digit3*100000 + digit4*10000 + digit5*1000 + digit6*100 + digit7*10 + digit8;
System.out.println(decimal_version);
Change the last bit of 8-digit number:
num ^= 1B
I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.
This question already has answers here:
How to convert binary string value to decimal
(15 answers)
Closed 5 years ago.
I tried to write a code that convert binary to decimal. But it gives me a huge result. Can you please tell me how to do it. I saw codes using remainder and give correct results but I really wonder what is the fault there in my code, thanks
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
Here is where your code went wrong:
str.charAt(16-1 - i) * Math.pow(2, i);
You just multiplied a char by a double. This will evaluate to the ASCII value of char times the double, not 0 or 1.
You need to convert this to an integer first:
Integer.parseInt(Character.toString(str.charAt(16-1 - i))) * Math.pow(2, i)
Or, you can just:
Integer.parseInt(binaryString, 2)
People here have already answered what went wrong. Doing Math.pow(2, i) on a character produced inconsistent result.
If you are going to convert binary value to an Integer this could help you.
Integer.parseInt(binaryString, 2)
Where the value 2 is the radix value.
Java documentation and similar SO Discussion on the same topic is available here.
When you use str.charAt(16-1-i), you get back a char, which represents a single letter. So you don't get the number 0 or 1, but the corresponding letters. As letters are represented as integers in Java, you don't get a type error. The number to represent a 0 letter is 48, for 1 it's 49. To convert your letter into the correct number, you have to write (str.charAt(16-1-i)-48) instead of str.charAt(16-1-i).
This question already has answers here:
How to Convert an int to a String? [duplicate]
(6 answers)
Closed 8 years ago.
I'm trying to create a method which generates a 4 digit integer and stores it in a string.
The 4 digit integer must lie between 1000 and below 10000. Then the value must be stored to PINString.
Heres what I have so far. I get the error Cannot invoke toString(String) on the primitive type int. How can I fix it?
public void generatePIN()
{
//generate a 4 digit integer 1000 <10000
int randomPIN = (int)(Math.random()*9000)+1000;
//Store integer in a string
randomPIN.toString(PINString);
}
You want to use PINString = String.valueOf(randomPIN);
Make a String variable, concat the generated int value in it:
int randomPIN = (int)(Math.random()*9000)+1000;
String val = ""+randomPIN;
OR even more simple
String val = ""+((int)(Math.random()*9000)+1000);
Can't get any more simple than this ;)
randomPIN is a primitive datatype.
If you want to store the integer value in a String, use String.valueOf:
String pin = String.valueOf(randomPIN);
Use a string to store the value:
String PINString= String.valueOf(randomPIN);
Try this approach. The x is just the first digit. It is from 1 to 9.
Then you append it to another number which has at most 3 digits.
public String generatePIN()
{
int x = (int)(Math.random() * 9);
x = x + 1;
String randomPIN = (x + "") + ( ((int)(Math.random()*1000)) + "" );
return randomPIN;
}
I'm trying to figure out how I could use a java program to return the last 3 digits of an integer.
So for example if I had a number like 45678 how would I be able to return 678? Also how would I be able to determine that the length of this integer is 5 digits?
You can determine how many digits a number has by using Math.log10() (remember to Math.abs() if you're going to be dealing with negatives):
(int) Math.log10(45678) + 1 // 5
Using the modulo operator with Math.pow() can give you the last x digits of a number:
int x = 3;
45678 % Math.pow(10, x) // 678
String s = Integer.toString(45678);
s.substring(s.length() - 3); // first answer
s.length() == 5; // second answer