Inputting String and Convert to ASCII - java

My problem is that when i input "b" it converts correctly but when i input other letters it just displaying the conversion of "b"
char ch = 'b';
int ascii = ch;
int castAscii = (int) ch;
DisplayText.setText(UserInput.getText() + " = " + castAscii);

This is because you only convert the character b to it's ascii value and not the actual user input. Assuming that UserInput.getText() returns the user defined character as character and not string:
int castAscii = (int) UserInput.getText();
DisplayText.setText(UserInput.getText() + " = " + castAscii);
In case UserInput.getText() returns a string, you can convert it into a character array and then iterate through it to combine the output.
String userInput = UserInput.getText();
String output = userInput + "=";
for (int i = 0; i < userInput.length(); i++) {
int castAscii = (int) userInput.toCharArray()[i];
output += castAscii;
if (i < userInput.length()) {
output += ",";
}
}
DisplayText.setText(output);
Using a framework like apache commons-lang would make for a more elegant solution, but this will work.

you set the ch='b'.so always you convert the "b" and ignore the input.
you must set the ch to what the user entered.
as I mentioned in comments,this is an example code to clarify the process.
String s = "hello";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
int ascii = (int) chars[i];
System.out.println(ascii);
}
you can write scanner.nextline() instead of "hello" next to String s to get the string from the user.

Related

int and char concatenation in java [duplicate]

This question already has answers here:
char + int gives unexpected result
(3 answers)
Closed 2 years ago.
This program receives a word as an input, and if the length of the word is greater than 10, then it should print the first letter of the word, then the number of characters in between the first and last letter, followed by the last letter. Such an input like "introduction" should output i10n. However, when I try concatenating each of them, something goes wrong, so it just outputs 224, which I have no clue why. Why does this happen, and how can I fix this issue? Any help would be appreciated.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String word = sc.next();
if (word.length() > 10){
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
System.out.println(firstChar + lettersInBetween + lastChar);
}
else {
System.out.println(word);
}
}
}
}
Try this:
System.out.println(firstChar + Integer.toString(lettersInBetween) + lastChar);
About the output of the number 224, this explains it very well:
https://en.wikipedia.org/wiki/ASCII
"For example, lowercase i would be represented in the ASCII encoding by binary 1101001 = hexadecimal 69 (i is the ninth letter) = decimal 105."
just replace line :
System.out.println(firstChar + lettersInBetween + lastChar);
with below line :
System.out.println(""+firstChar + lettersInBetween + lastChar);
The easiest way of joining multiple String and numeric values in Java. Just remember that, when you have two or more primitive type values e.g. char, short, or int, at the beginning of your string concatenation, you need to explicitly convert the first of them to a String.
String.valueOf(int i) method takes an integer value as an argument and returns a string representing the int argument.
Integer.toString(int i) method works same as String.valueOf(int i) method. It belongs to the Integer class and converts the specified integer value to String. for e.g. if the passed value is 101 then the returned string value would be “101”.
You can you both of these methods to convert the integer to String.
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
String number = String.valueOf(lettersInBetween);
System.out.println(firstChar + number + lastChar);
or
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
String number = Integer.toString(lettersInBetween);
System.out.println(firstChar + number + lastChar);

How do I get each number a user inputs as set of numbers in string with each number separated by a space?

For example, the user enters "1 2 3 4", how do I extract those four numbers and put them into separate spots in an array?
I'm just a beginner so please excuse my lack of knowledge.
for (int i = 0; i < students; i++) {
scanner.nextLine();
tempScores[i] = scanner.nextLine();
tempScores[i] = tempScores[i] + " ";
tempNum = "";
int scoreCount = 0;
for (int a = 0; a < tempScores[i].length(); a++) {
System.out.println("Scorecount " + scoreCount + " a " + a );
if (tempScores[i].charAt(a) != ' ') {
tempNum = tempNum + tempScores[i].charAt(a);
} else if (tempScores[i].charAt(a) == ' ') {
scores[scoreCount] = Integer.valueOf(tempNum);
tempNum = "";
scoreCount ++;
}
}
You can use String.split(String) which takes a regular expression, \\s+ matches one or more white space characters. Then you can use Integer.parseInt(String) to parse the String(s) to int(s). Finally, you can use Arrays.toString(int[]) to display your int[]. Something like
String line = "1 2 3 4";
String[] tokens = line.split("\\s+");
int[] values = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
values[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(values));
Outputs
[1, 2, 3, 4]
If you are very sure that the numbers will be separated by space then you could just use the split() method in String like below and parse individually :
String input = sc.nextLine(); (Use an sc.hasNextLine() check first)
if (input != null || !input.trim().isEmpty()) {
String [] numStrings = input.split(" ");
// convert the numbers as String to actually numbers by using
Integer.parseInt(String num) method.
}

Check if charAt are the same (case sensitive)

Im have to write a method to check if a word is a palindrome. There is probably a easier way then I have it but this is just based off what I have learned so far. My method works except if there is a capital letters compared to a lowercase.
Edit: wasn't very clear. My method returns that a capital and lower case letter are the same. But I would like it to say they are different
public static void printPalindrome(Scanner kb) {
System.out.print("Type one or more words: ");
String s = kb.nextLine();
int count = 0;
for(int i = 0; i < s.length();i++) {
char a = s.charAt(i);
char b = s.charAt(s.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
if (count == s.length()) {
System.out.print(s + " is a palindrome!");
} else {
System.out.print(s + " is not a palindrome.");
}
}
I'd recommend a slightly different approach, I'd reverse the string using StringBuilder#reverse and then compare the two strings using String#equalsIgnoreCase
String s = kb.nextLine();
StringBuilder sb = new StringBuilder(s).reverse();
if (s.equalsIgnoreCase(sb.toString())) {
...
} else {
...
}
You can solve your problem by converting the input String to upper case :
String s = kb.nextLine().toUpperCase();
Or if you wish to preserve the case of the original String, create a new String and test if it's a palindrome.
String s = kb.nextLine();
String u = s.toUpperCase();
int count = 0;
for(int i = 0; i < u.length();i++) {
char a = u.charAt(i);
char b = u.charAt(u.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
i think you can do it with its ascii values
look this picture
then you shoul convert your char to ascii
char character = 'a';
int ascii = (int) character;
then compare the integers

convert String to ASCII and ASCII to String

This is my code to convert String to ASCII and ASCII to String. I have problem when the user enter text with spaces the all texts didn't convert but if i wrote the text in program the text converted . This is my input "Java is easy"
String str = input.next();
//String str = "Java is easy";
char ch[] = str.toCharArray();
int num[] = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
System.out.print((int)ch[i] + " ");
num[i] = (int)ch[i];
}
System.out.println("");
for (int j = 0; j < str.length(); j++) {
System.out.print((char)num[j]);
}
System.out.println("");
Scanner.next() reads a single word, i.e. "Java".
Scanner.nextLine() reads an entire line, i.e. "Java is easy"
You should change
String str = input.next();
to
String str = input.nextLine();

Converting a string into its respective unicode ints and back only using strings and ints

Well my assignment is to convert a string into its respective unicode ints, shift based on the desired encryption (left or right and how many spaces). I was able to figure this part out just fine. But then I need to enter the shifted string of unicode and convert that back into the original string entered. Here is my code. I can't figure out how to convert the unicode string back into the original string.
**Note - I AM ONLY ALLOWED TO USE INTS AND STRINGS.
import java.util.Scanner;
import java.lang.String;
import java.lang.Character;
public class CSCD210_HW2
{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str, str1 = "";
String encrypt, decrypt = "";
int i = 0;
int i1 = (int)0;
System.out.printf("Please enter a string:");
str = input.nextLine();
System.out.printf("\nPlease enter encryption format - \'left\' or \'right\'" +
" \"space\" number of spaces:");
encrypt = input.nextLine();
int length = str.length();
String spaces = encrypt.substring(encrypt.lastIndexOf(' ') + 1);
Integer x = Integer.valueOf(spaces);
//encrypt
if (encrypt.startsWith("l")){
while (i < length){
int uni = (int)(str.charAt(i++));
char uni1 = (char)uni;
int result = uni + x;
System.out.print(result + " ");}}
else if (encrypt.startsWith("r")){
while (i < length){
int uni = (int)(str.charAt(i++));
char uni1 = (char)uni;
int result = uni - x;
System.out.print(result + " ");}}
//decrypt
System.out.printf("\nPlease enter encrypted string:");
str1 = input.nextLine();
System.out.printf("\n\'left\' or \'right\' \"space\" number of spaces:");
decrypt = input.nextLine();
int length1 = str1.length();
String spaces1 = decrypt.substring(decrypt.lastIndexOf(' ') + 1);
Integer y = Integer.valueOf(spaces1);
if (decrypt.startsWith("l")){
while (i < length1){
char word = (char)(str1.charAt(i++));
int result = word + y;
System.out.print(result);}}
else if (decrypt.startsWith("r")){
while (i < length1){
char word = (char)(str1.charAt(i++));
int result = word - y;
System.out.print(result);}}
}
}
Your second part does not make sense as you have the encrypted values which are basically 3 digits for a single character. You need therefore a way to convert the 3 numbers back into 1 character and not create a character per number.
Replace this with your second part:
// split the input line containing the encrypted values into single tokens
// each token represents the numerical values of a single character
String[] tokens = str1.split("\\s");
// reserve some space for the characters
// char[] chars = new char[tokens.length];
String chars = "";
// keep track of the position
// int pos = 0;
for (String token : tokens)
{
if (decrypt.startsWith("l"))
{
// convert the string containing the number to integer
Integer val = Integer.parseInt(token);
// convert the integer back to char and apply the transformation
// chars[pos++] = ((char)(val.intValue()+y));
chars += ((char)(val.intValue()+y));
}
else
{
// convert the string containing the number to integer
Integer val = Integer.parseInt(token);
// convert the integer back to char and apply the transformation
// chars[pos++] = ((char)(val.intValue()-y));
chars += ((char)(val.intValue()-y));
}
}
// check if everything worked as expected
System.out.println(chars);
// System.out.println(new String(chars));
#Edit:
UPDATED to the needs of the OP

Categories