int and char concatenation in java [duplicate] - java

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);

Related

How to identify which characters are mismatching in a user input string

This project is used to identify whether or not a user's input is a palindrome, and if it's not, identifies how many characters don't match and their positions in the string (i.e characters 2 and 4 don't match). I've been able to figure out how to identify whether or not a string is a palindrome, but I'm struggling with how to specifically identify the characters that don't match in a non-palindrome. Here's my code so far:
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
String stringInput = "";
String inputReverse = "";
boolean isPalindrome = true;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
stringInput = keyboard.nextLine();
int stringLength = stringInput.length();
for(int i = stringLength - 1; i >=0; i--)
{
inputReverse = inputReverse + stringInput.charAt(i);
}
if(stringInput.equals(inputReverse))
{
System.out.println(stringInput + " is a valid palindrome.");
}
else
{
System.out.println(stringInput + " is not a valid palindrome.");
}
}
}
the output I want for when a string is not a palindrome is:
"The characters at index 0 and 3 do not match.
goop is not a valid palindrome.
number of invalid character matches: 1 "
I tried to use stringInput.charAt(0) but the user input is unpredictable, so I wouldn't be able to use char 0,1,2,3 etc forever. Any help?
Iterate from both ends of the string, moving toward the center and checking the corresponding characters each time.
int nomatch = 0;
for (int i = 0, j = stringLength - 1; i < j; i++, j--) {
if (stringInput.charAt(i) != stringInput.charAt(j)) {
++nomatch;
System.out.format("The characters at index %d and %d do not match.%n", i, j);
}
}
if (nomatch == 0) System.out.println(stringInput + " is a palindrome.");
else System.out.println(stringInput + " is not a palindrome. Number of invalid character matches: " + nomatch);
As this is home work, I'll only give general hints:
an easy way to reverse a string is inputReverse = new StringBuilder(stringInput).reverse().toString();
you only need to compare each character of the first half of the input with its reverse
use a for loop of int from 0 to half the length and pass it to charAt() for both strings and compare using ==
store the indexes of differences in a List<Integer>

How do I write a converting (lowercase->uppercase, single digits->double its value, two digits->sum of its digits) program w/ letters & numbers?

I was tasked to write a function that takes in user input as a string. For all characters which are numeric, double its value and, if it is
two digits, then replace it with the sum of its digits (e.g., 6 → 12 → 3 whereas 3 → 6). For all characters which are in uppercase, replace it with lowercase. For all characters which are in lowercase, replace it with uppercase (e.g., m → M and N → n). The program should keep asking the user to enter strings until they either enter ‘q’ or
‘Q’ to quit.
I have this so far, which works for the conversion of the letters. I'm not sure how to implement the other part into it and where it would go.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1;
System.out.print("Enter string: ");
str1 = scan.nextLine();
StringBuffer newStr = new StringBuffer(str1);
for (int i = 0; i < str1.length(); i++) {
//Checks for lower case character
if (Character.isLowerCase(str1.charAt(i))) {
//Convert it into upper case using toUpperCase() function
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
//Checks for upper case character
else if (Character.isUpperCase(str1.charAt(i))) {
//Convert it into upper case using toLowerCase() function
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after conversion : " + newStr);
}
}
here is my approach
public static String conversion(String inputString){
String out = "";
for(char c:inputString.toCharArray()){
if(Character.isDigit(c)){
int num = Integer.parseInt(String.valueOf(c))*2;
if(num>=10){
char[] parts = String.valueOf(num).toCharArray();
int sum = 0;
sum+=Integer.parseInt(String.valueOf(parts[0]));
sum+=Integer.parseInt(String.valueOf(parts[1]));
out+=sum;
}else out+=num;
}else{
if(Character.isUpperCase(c)) out+=Character.toLowerCase(c);
else out+=Character.toUpperCase(c);
}
}
return out;
}

Inputting String and Convert to ASCII

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.

Regular Expressions - match a string containing "+" and "-"

I have a string, say 1+++-3--+++++2 that includes + and - sign.
What I want to do is to represent the + and - part with + or - sign.
If there are an odd number of - sign in the string, I will replace it with -, and + if that is an even number. How can I do that using regex?
For example, I have a math expression, say 1+-+-2-+--+3. It will be replaced by 1+2-3
You can create an array of the operators and use a for loop to count all occurrences of one character. For example:
String expression = "1+++-3--+++++2";
String[] str = expression.split("[0-9]+");
for(op : str) {
int count = 0;
for(int i =0; i < str.length(); i++)
if(op.charAt(i) == '-')
count++;
if(count % 2 == 0) {
op = "-";
}
else {
op = "+";
}
}
After assigning the modified one-character operators in str[], it should be relatively simple to write the new expression.
based on the assumption that the format will be from that calculator example.
//assumed format for input: <any number><any number of `-` and/or `+`><any number>
// 1++---+22+--1 will be 1-22+1
String input = "1++---+22+--1";
for (String s : input.split("[^-+]+");) {
s = s.trim();
if (!"".equals(s)) {
String newStr = s.matches("[+]*-([+]*-[+]*-)*[+]*") ? "-" : "+";
input = input.replace(s, newStr);
}
}
System.out.println(input);

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