Converting a int to char [duplicate] - java

This question already has answers here:
Java - Change int to ascii
(9 answers)
Closed 5 years ago.
I am looking to convert numbers to their corresponding letter in the alphabet.

As seen here alphabetical characters start from either 65 or 97 (depending on capitalization) so you just add either 64 or 96 to your value and then just cast it to a char.
Random rand = new Random();
int TargetNumber = rand.nextInt(25) + 1;
char TargetChar = (char) (TargetNumber+64);

Try this
Random rand = new Random();
int TargetNumber = rand.nextInt(25) + 1;
char c = (char)(TargetNumber+96);
This adds 96 to the generated value, and then type casts it into a char. This works for a-z. To make it through A-Z replace 96, by 64.

i think you can do this:
char a = (char)20;

Related

(char) (i + 'a') JAVA: what's happening here? [duplicate]

This question already has answers here:
Adding and subtracting chars, why does this work? [duplicate]
(4 answers)
Parentheses around data type?
(5 answers)
What does a 'int' in parenthesis mean when giving a value to an int?
(7 answers)
What is the purpose and meaning of (char)i or (int)i in java?
(3 answers)
Closed 2 years ago.
I encountered a similar piece of code:
public class print {
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.print((char) (i + 'a'));
}
}
}
If I run it, I get "abcdef".
My question regards this expression: (char) (i + 'a').
I kind of intuitively get what's going on, but I want a rigorous step-by-step explanation of how the computer translates it. As indicated in some answers, the char is simply a number displayed as a character. Fine, but what does this syntax with parentheses actually do? Is it a conversion? Can I use it for other types as well?
The ASCII value of a is 97.
When i = 0, i + 'a' = 0 + 97 => When cast into char, it will be a
When i = 1, i + 'a' = 1 + 97 => When cast into char, it will be b
When i = 2, i + 'a' = 2 + 97 => When cast into char, it will be c
...and so on
Java char is a 16-bit integral type. 'a' is the same as 97, which you can see with System.out.println((int) 'a'); - it follows that 98 is 'b' and so on across the entire ASCII table.
You can use char as an integer value and vise versa
Below code may help:
char aChar = 'a'; // a char
int aCharAscii = aChar; // 97
char bChar = 'a' + 1; // b char
int bCharAscii = aChar + 1; // 98

Generate 6 digit random number [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I just want to generate 6 digit random number, and the range should be start from 000000 to 999999.
new Random().nextInt(999999) is returning me number but it is not in 6 digit.
Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);
this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
// It will generate 6 digit random Number.
// from 0 to 999999
Random rnd = new Random();
int number = rnd.nextInt(999999);
// this will convert any number sequence into 6 character.
return String.format("%06d", number);
}
If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;
Leading zeros do not have effect, 000000 is the same as 0. You can further simplify it with ThreadLocalRandom if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)
1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].
already solved here
public int gen()
{
Random r = new Random( System.currentTimeMillis() );
return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}
i know it’s very difficult but you can do something like this:
create a class for BinaryNumber;
create a constructor that generate a char[] of 6 character where every single one is generated with a randomiser from 0 to 1
override the toStrig() method so that it will return the digits char[] as a string if you want to display it. then crate a method toInt() that esaminate the string char by char with a for and turn it in a decimal base number by multiplying current digit to 10 to the pow of i:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’};
//random
int result = 0;
for( int i = 0; i < digits.length; i++) {
result += Integer.parseInt(digits[i]) * Math.pow(10, i);
}
return result;
This is the code in java which generate a 6 digit random code.
import java.util.*;
public class HelloWorld{
public static void main(String []args)
{
Random r=new Random();
HashSet<Integer> set= new HashSet<Integer>();
while(set.size()<1)
{
int ran=r.nextInt(99)+100000;
set.add(ran);
}
int len = 6;
String random=String.valueOf(len);
for(int random1:set)
{
System.out.println(random1);
random=Integer.toString(random1);
}
}
}

Why is myArrayList.size(); producing incorrect/gigantic numbers?

Basically, I'm trying to write a program that converts a number from base 2 to base 10. What I tried doing was translating the process listed on this website under the "Doubling method" into a for loop, but for some reason the numbers I'm getting are way to big.
The basic formula is (2 * previousTotal) + (currentDigit of the ArrayList that holds the user's inputted binary number) = previousTotal.
So for 1011001 in binary, the math would be:
(0 x 2) + 1 = 1
(1 x 2) + 0 = 2
(2 x 2) + 1 = 5
(5 x 2) + 1 = 11
(11x 2) + 0 = 22
(22 x 2) + 0 = 44
(44 x 2) + 1 = 89
The console however, prints out 6185 as the result. I'm thinking it might have something to do with me using an ArrayList of characters, but the charWhole.size() returns 7, which is how many digits are in the user's binary number. As soon as I do charsWhole.get(w); however, I start getting big numbers such as 49. I'd really appreciate some help!
I wrote out this loop, and according to some print statements that I placed throughout the code and my variable addThis seems to be where the problem is. The console prints out a final total of 6185, when 1011001 in base 10 is actually 89.
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
You are attempting to add a character to an integer. The implicit conversion uses the ASCII value of the character, so that '1' gets converted to 49, not 1, because 49 is the code for the character '1'. Subtract '0' to get the actual integer value.
addThis = charsWhole.get(w) - '0';
This works because the digits 0-9 are represented in ASCII as the codes 48-57, so in effect you will, for '1', subtract 49 - 48 to get 1.
You'll still have to handle cases when the character is outside the range of allowable characters.
EDIT
Java uses Unicode, but for the purposes of the codes for the digits 0-9, the codes are the same (48 thru 57, or 0x30 thru 0x39) in both ASCII and Unicode.
The problem is that you're using the chars rather than the number value they represent. In the line
addThis = charsWhole.get(w);
the value of addThis is the ascii value of the character. For '0', this is 48. Use this instead:
addThis = Integer.parseInt(charsWhole.get(w));
Another suggestion to solve the same problem:
addThis = charsWhole.getNumericValue(w);
See here for more information.

Shift character in Alphabet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ROT-13 function in java?
I have to shift all char from a string 13 places in the alphabet
private static String encode(String line) {
char[] toEncode = line.toCharArray();
for (int i = 0; i < toEncode.length; i++) {
if (Character.isLetter(toEncode[i])) {
toEncode[i] += 13;
}
}
line = String.valueOf(toEncode);
return line;
}
The Problem is that for example 'z' get to a ?. How can I solve that?
Thx for help.
It is because next chars after 'z' is punctuation chars and so on. You can shift so that 'z' will be 'n' for example.
toEncode[i] = (toEncode[i] + 13 - (int)'a') % 26 + (int)'a';
System.out.println(('z'+ (char)13)); //output -135
System.out.println((char)('z'+ (char)13)); //output - ?
If the calculated char is greater than the last letter (z => 122 or Z => 90) just substract the value of the last letter from the calculated value. You find these numbers all over the internet, e.g. here.

What's the "java" way of converting chars (digits) to ints [duplicate]

This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 2 years ago.
Given the following code:
char x = '5';
int a0 = x - '0'; // 0
int a1 = Integer.parseInt(x + ""); // 1
int a2 = Integer.parseInt(Character.toString(x)); // 2
int a3 = Character.digit(x, 10); // 3
int a4 = Character.getNumericValue(x); // 4
System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);
(version 4 credited to: casablanca)
What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)
We are not converting the actual numerical value of the char, but the value of the representation.
Eg.:
convert('1') -> 1
convert('2') -> 2
....
How about Character.getNumericValue?
I'd strongly prefer Character.digit.
The first method. It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages. Of course, its error handling leaves something to be desired.
If speed is critical (rather than validation you can combine the result)
e.g.
char d0 = '0';
char d1 = '4';
char d2 = '2';
int value = d0 * 100 + d1 * 10 + d2 - '0' * 111;
Convert to Ascii then subtract 48.
(int) '7' would be 55
((int) '7') - 48 = 7
((int) '9') - 48 = 9
The best way to convert a character of a valid digit to an int value is below. If c is larger than 9 then c was not a digit. Nothing that I know of is faster than this. Any digits in ASCII code 0-9(48-57) ^ to '0'(48) will always yield 0-9. From 0 to 65535 only 48 to 57 yield 0 to 9 in their respective order.
int charValue = (charC ^ '0');

Categories

Resources