How to treat a string as a variable in java? - java

Remember playing the game when you indexed each of the words of your name and added it all together to form a secret number? Like aay would be 1+1+25=27
I tried to do the same thing by various methods in java but I failed.Let me share my script first and then tell what all i tried.
class test{
public static void main(String args[]){
int c = 3;
String s = "c";
///now this is what all i tried:
int value1 = (int)(s);
///i tried a cast, but that failed.
String d = "4";
int value2 = Integer.parseInt(d);
///when i try this, it correctly converts the string to an integer.
Integer.parseInt(s);
///but when i try the above, it fails to do the same.
}
}
In this code, I try 2 different methods both of which are working in a similar way that I want to but not exact.
The problem is that it couldn't reorganize that c is a variable that has an integer value.
So, is there any shortcut to do it?
Also, right now the string is only 1 digit long, once the user inputs his or her name, I shall use a for loop to loop all of the letters completely.
If there isn't any shortcut, is the only option left with me is to make an if statement like:
if(letter=a;){
value=1;
}
Or something like that?
thanks for helping!

You can't convert a String directly into an integer, you need to take one character at a time and subtract the value of the char 'a' then add 1 :
public static void main(String[] a) {
String s = "test";
for (char c : s.toLowerCase().toCharArray()){
System.out.println(charToInt(c));
}
}
private static int charToInt(char c){
return c - 'a' + 1;
}

In Java like most other C-eqsue languages, char is a Number type.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff'
(or 65,535 inclusive).
Just Alphabetic Characters
So all you need to do is convert each character to its equivilent char and you have its ASCII/Unicode value; I won't go into Unicode here, because ASCII maps over Unicode into the correct place.
// this will give you a Zero based int of the
// UPPPERCASE alphabet which starts at `65` and
// ends at `90`.
// See where the lowercases starts and ends?
char c = "My Name".charAt(0) - 65;
// c = 'M' in this case which is 77 - 65 = 12
The ASCII codes are easy to translate.
(source: asciitable.com)
For UPPERCASE letters it is just an exercise of looping through all the chars of a String and getting their code and subtracting 65 to get a 0 based value. It gets a little more complicated to exclude other characters and process lowercase as well, but you get the idea from the table.
Printable Characters
Notice "printable" characters start at 32 and run through 126 which is usually what you just do, is subtract 32 instead of 65 and just convert all "printable" characters to a Zero base.
Example
The following will print out all the "printable" characters.
public class Main
{
public static void main(final String[] args)
{
for (char i = 32; i <= 126; i++)
{
System.out.println(new Character(i));
}
}
}
Solution
Here is a complete solution that will create a secret code, of all the *"printable" characters possible.
public class Main
{
public static void main(final String[] args)
{
int hash = 0;
final String s = args[0];
for (int c = 0; c < s.length(); c++)
{
hash = hash + s.charAt(c) - 32;
}
System.out.printf("Secret code for %s is %d", s, hash);
}
}
the result for my name is
Secret code for Jarrod is 418

Related

Extremely compact UUID (using all alphanumeric characters)

I need an extremely compact UUID, the shorter the better.
To that end, I wrote:
public String getBase36UIID() {
// More compact version of UUID
String strUUID = UUID.randomUUID().toString().replace("-", "");
return new BigInteger(strUUID, 16).toString(36);
}
By executing this code, I get, for example:
5luppaye6086d5wp4fqyz57xb
That's good, but it's not the best. Base 36 uses all numeric digits and lowercase letters, but does not use uppercase letters.
If it were possible to use uppercase letters as separate digits from lowercase letters, it would be possible to theorize a numerical base 62, composed of these digits:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
I could theorize numerical bases also using accented characters such as "รจ" or "รฉ", or special characters such as "$" or "!", further increasing the number of digits available.
The use of these accented or special characters, however, may cause me problems, so for the moment I prefer not to consider them.
After all these premises, how can I convert the BigInteger representing my UUID into the base 62 above theorized, in order to make it even more compact? Thanks
I have already verified that a code like the following is not usable, because every base over 36 is treated as base 10:
return new BigInteger(strUUID, 16).toString(62);
After all, in mathematics there is no base 62 as I imagined it, but I suppose that in Java it can be created.
The general algorithm for converting a number to any base is based on division with remainder.
You start by dividing the number by the base. The remainder gives you the last digit of the number - you map it to a symbol. If the quotient is nonzero, you divide it by the base. The remainder gives you the second to last digit. And you repeat the process with the quotient.
In Java, with BigInteger:
String toBase62(BigInteger number) {
String symbols = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
BigInteger base = BigInteger.valueOf(symbols.length());
StringBuilder result = new StringBuilder();
do {
BigInteger[] quotientAndRemainder = number.divideAndRemainder(base);
number = quotientAndRemainder[0];
result.append(symbols.charAt(quotientAndRemainder[1].intValue()));
} while (number.compareTo(BigInteger.ZERO) > 0);
return result.reverse().toString();
}
Do you need the identifier to be a UUID though? Couldn't it be just any random sequence of letters and numbers? If that's acceptable, you don't have to deal with number base conversions.
String randomString(int length) {
String symbols = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
StringBuilder str = new StringBuilder();
for (int i = 0; i < length; i++) {
str.append(symbols.charAt(rnd.nextInt(symbols.length())));
}
return str.toString();
}
This should not be difficult. Converting a number to a string is a basic programming task. The fact that you're using base 62 makes no difference.
Decide how many characters you're willing to use, and then convert your large number to that base. Map each "digit" onto one of the characters.
Pseudocode:
b = the base (say, 62)
valid_chars = an array of 'b' characters
u = the uuid
while u != 0:
digit = u % b;
char = valid_chars[digit];
u = u / b;
This produces the digits right-to-left but you should get the idea.
Main idea is the same as previous posts, but the implementation have some differences.
Also note that if wanted different occurrence probability for each chars this can be adjusted also.(mainly add a character more time on a data structure and change his probability)
Here is fair-probability for each chars (equals, 1/62)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RCode {
String symbols = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args)
{
RCode r = new RCode();
System.out.println("symbols="+r.symbols.length());
System.out.println("code_10(+1)="+r.generate(10));
System.out.println("code_70(+2)="+r.generate(70));
//System.out.println("code_124(+3)="+r.generate(124));
}
public String generate(int length)
{
int num = length/symbols.length()+1;
List<Character> list = new ArrayList<Character>();
for(int i=0; i<symbols.length(); i++)
{
//if needed to change probability of char occurrence then adapt here
for(int j=0;j<=num;j++)
{
list.add(symbols.charAt(i));
}
}
//basically is the same as random
Collections.shuffle(list);
StringBuffer sb = new StringBuffer();
for(int i=0; i<length; i++)
{
sb.append(list.get(i));
}
return sb.toString();
}
}
Output:
symbols=62
//each char is added once(+1)
code_10(+1)=hFW9ZFEAeU
code_70(+2)=hrHQCEdQ3F28apcJPnfjAaOu55Xso12xabkJ7MrU97U0HYkYhWwGEqVAiLOp3X3QSuq6qp
Note: Algorithm have a defect, just try to figured out why the sequence will be never generate on 10 (aaaaaaaaaa). Easy to fix ... but i was focused on the idea.
Now, as it is, basically is generating up to num each character. (random and maybe for someone will be useful the output)

Java: How do I loop through characters in a string that have a surrogate pair and print them?

I tried this to loop through the characters in my string and print them. All of them are printing fine except the Deseret Long I (๐€). I have no idea if there are other ways to do this so that the ๐€ is printed correctly. Here is my code:
package javaapplication13;
public class JavaApplication13 {
public static void main(String[] args) {
String s = "h๐คกy๐€\u0500";
System.out.println(s);
final int length = s.length();
for (int offset = 0; offset < length;) {
final int codepoint = s.codePointAt(offset);
System.out.println((char) (codepoint));
offset += Character.charCount(codepoint);
}
}
}
The output looks like this (Netbeans):
run:
h๐คกy๐€ิ€
h
ไก
y
ะ€
ิ€
BUILD SUCCESSFUL (total time: 0 seconds)
Your problem is caused by the fact that you try to convert int to char (4 bytes to 2 bytes). The value in the codepoint variable cannot fit in one char in case of surrogate pair. Look, it is called pair, because it is a pair of chars. I think the simplest way how you can print it is by using String.Substring() method. Or you can convert it to array of char's this way: char[] ch = Character.toChars(codepoint); and you can convert this array back to string by simple new String(ch).

The text within a String is rearranged after being submitted and returned back

I'm creating a program that takes single any characters between the ASCII codes of 32 - 126 and returns the result as Binary. It's a bunch of if statements with .contains("")'s. The code works when returning single characters, but when entering words, the Strings come back in binary re-alphabetized. So if I enter in the name Lauren it comes out in Binary like this: 010011000110000101100101011011100111001001110101-Laenru (capitals come first still).
Here's all my code:
Main.java
import java.util.Scanner;
public class Main {
public static Scanner input = new Scanner(System.in);
public static void main (String[] args) {
Letters l = new Letters();
l.Letters();
}
}
Letters.java
public class Letters extends Main {
#SuppressWarnings("null")
public static void Letters () {
System.out.println("Enter your letter(s)");
String givenLetters = input.next();
if (givenLetters.contains("A"))
System.out.println("01000001");
if (givenLetters.contains("B"))
System.out.println("01000010");
if (givenLetters.contains("C"))
System.out.println("01000011");
if (givenLetters.contains("D"))
System.out.println("01000100");
if (givenLetters.contains("E"))
System.out.println("01000101");
if (givenLetters.contains("F"))
System.out.println("01000110");
if (givenLetters.contains("G"))
System.out.println("01000111");
if (givenLetters.contains("H"))
System.out.println("01001000");
if (givenLetters.contains("I"))
System.out.println("01001001");
if (givenLetters.contains("J"))
System.out.println("01001010");
if (givenLetters.contains("K"))
System.out.println("01001011");
if (givenLetters.contains("L"))
System.out.println("01001100");
if (givenLetters.contains("M"))
System.out.println("01001101");
if (givenLetters.contains("N"))
System.out.println("01001110");
if (givenLetters.contains("O"))
System.out.println("01001111");
if (givenLetters.contains("P"))
System.out.println("01010000");
if (givenLetters.contains("Q"))
System.out.println("01010001");
if (givenLetters.contains("R"))
System.out.println("01010010");
if (givenLetters.contains("S"))
System.out.println("01010011");
if (givenLetters.contains("T"))
System.out.println("01010100");
if (givenLetters.contains("U"))
System.out.println("01010101");
if (givenLetters.contains("V"))
System.out.println("01010110");
if (givenLetters.contains("W"))
System.out.println("01010111");
if (givenLetters.contains("X"))
System.out.println("01011000");
if (givenLetters.contains("Y"))
System.out.println("01011001");
if (givenLetters.contains("Z"))
System.out.println("01011010");
if (givenLetters.contains(" "))
System.out.println("00100000");
if (givenLetters.contains("a"))
System.out.println("01100001");
if (givenLetters.contains("b"))
System.out.println("01100010");
if (givenLetters.contains("c"))
System.out.println("01100011");
if (givenLetters.contains("d"))
System.out.println("01100100");
if (givenLetters.contains("e"))
System.out.println("01100101");
if (givenLetters.contains("f"))
System.out.println("01100110");
if (givenLetters.contains("g"))
System.out.println("01100111");
if (givenLetters.contains("h"))
System.out.println("01101000");
if (givenLetters.contains("i"))
System.out.println("01101001");
if (givenLetters.contains("j"))
System.out.println("01101010");
if (givenLetters.contains("k"))
System.out.println("01101011");
if (givenLetters.contains("l"))
System.out.println("01101100");
if (givenLetters.contains("m"))
System.out.println("01101101");
if (givenLetters.contains("n"))
System.out.println("01101110");
if (givenLetters.contains("o"))
System.out.println("01101111");
if (givenLetters.contains("p"))
System.out.println("01110000");
if (givenLetters.contains("q"))
System.out.println("01110001");
if (givenLetters.contains("r"))
System.out.println("01110010");
if (givenLetters.contains("s"))
System.out.println("01110011");
if (givenLetters.contains("t"))
System.out.println("01110100");
if (givenLetters.contains("u"))
System.out.println("01110101");
if (givenLetters.contains("v"))
System.out.println("01110110");
if (givenLetters.contains("w"))
System.out.println("01110111");
if (givenLetters.contains("x"))
System.out.println("01111000");
if (givenLetters.contains("y"))
System.out.println("01111001");
if (givenLetters.contains("z"))
System.out.println("01111010");
}
}
I want the String to come out the same way the user will have entered it if that means I have to add code to re-rearrange the letters or that I need to fix something in my buggy code.
Thanks in advanced! :)
try
String givenLetters = input.next();
for(char c : givenLetters.toCharArray()) {
if (c == 'A')
System.out.println("01000001");
....
or better create a map
static Map<Character, String> map = new HashMap<>();
static {
map.put('A', "01000001");
...
}
then the code will be
for(char c : givenLetters.toCharArray()) {
String s = map.get(c);
if (s != null) {
System.out.print(s);
}
...
You problem is that givenLetters.contains("X") returns true if the substring "X" is found anywhere in the string givenLetters. As Evgeniy Dorofeev suggests, what you should do instead is to loop over the characters in the string one by one.
Of course, using a huge list of if statements (or even a huge array) is a silly way to convert a character to binary. Instead, you can do it bit by bit (demo on ideone.com):
char[] bits = new char[8];
for (char c : givenLetters.toCharArray()) {
for (int i = 0; i < 8; i++) {
int bitmask = 1 << (7-i);
bits[i] = ((c & bitmask) == 0 ? '0' : '1');
}
System.out.println(bits);
}
(Note that Java chars are actually 16 bits long; this code will only print the lowest 8 bits of each.)
Two comments:
1) To loop through the characters in the string...
for(int i=0; i<givenLetters.length(); i++) {
char c = givenLetters.charAt(i);
System.out.println(code[c]);
}
2) Make an array with your code to avoid that nasty if statement
private static String code[255];
static {
code['A'] = "01000001";
code['B'] = "01000010";
(and so on)
That allows you to use System.out.println(code[c]) in place of that huge if chain.
If you want to literally put the binary on the same line, replace println with print

How can I extract the numbers from a string only using charAt(), length() and/or toCharArray() in Java

I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;

Generate all words using Java

I want to know how to generate all words using java from specified characters and length
String first[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String second[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String ch ="";
String total[];
for(int i = 0;i<26;i++) {
for(int j = 0;j<26;j++) {
ch+=first[i]+first[j];
System.out.println(ch);
}
}
I get only 576 words only by this program, but the 26! words is 4.03291461 ร— 10^26
How to write the program in java?
public class Words {
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
static void generate(StringBuilder sb, int n) {
if (n == sb.length()) {
System.out.println(sb.toString());
return;
}
for (char letter : alphabet) {
sb.setCharAt(n, letter);
generate(sb, n + 1);
}
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int length = 2; length <= 5; length++) {
sb.setLength(length);
generate(sb, 0);
}
}
}
This generates all 2-letters, 3-letters, 4-letters, and 5-letters "words". It uses a standard recursive algorithm.
See also
Given an array of integers [x0 x1 x2], how do you calculate all possible permutations from [0 0 0] to [x0 x1 x2]?
On a more mathematical note, people often confuse what the term "permutation" means. Yes, there are 26! permutations of the 26 letters a-z -- that's A LOT of strings, but this does not include aa, ab, etc. It includes all strings where the 26 letters each appear exactly once.
Consider what you're doing:
you're looping through the first array once, and looping through the second once for each iteration through that loop.
That's going to yield you a total of 26^2 results, or 676 (not 576).
And the way you're constructing the output is very specific, check what you get and you'll notice a highly explicit pattern in there.
The second array of course is never used at all, so completely superfluous.
The solution is to write out on paper how you'd go about it were you to attempt it by hand, then attempt to translate that into code.
For one you're not going to want to have only words of a specific length (which you get) or specific patterns of letters (which you also get).
but the 26! words is 4.03291461 ร— 1026
how to write the program in java
You don't write that program in Java or any other language. It would be pointless because it would literally take billions of years to finish.
But the number is also completely wrong for your intended result in the comments. 26! is the number of permutations, i.e. the different ways to order 26 elements without repetition. The number of words would be 26^n, where n is the length.
Here's my solution. It's kind of quick, so don't be too hard on the optimization.
public static void printWords(int length) {
if (length < 1)
throw new IllegalArgumentException();
printWordsRec("", length);
}
private static void printWordsRec(String base, int length) {
for (char c = 'a'; c <= 'z'; c++) {
if (length == 1) {
System.out.println(base + c);
}
else {
printWordsRec(base + c, length - 1);
}
}
}

Categories