I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value
Related
Here's my first question. I'm taking an online coding class, and it definitely has some holes in the instruction. We have been tasked with taking 2 different inputs that are one character only, and converting them to ASCII values. I have that down pat, I'm struggling with how I'm supposed to validate the inputs to only allow one character, and not something such as a number or symbol, and then exit the program if such an error arises. Here's my code.
import java.io.*;
import java.util.*;
public class AndrewBrutonMod4TopSecret
{
public static void main(String args[])
{
Scanner kaReader = new Scanner(System.in);
System.out.println("Enter the first initial of your first name:");
String i1 = kaReader.next();
System.out.println("Enter the first initial of your last name:");
String i2 = kaReader.next();
char a = i1.charAt(0);
char b = i2.charAt(0);
char a1 = Character.toUpperCase(a);
char b1 = Character.toUpperCase(b);
int c = (int)a;
int d = (int)b;
System.out.println("Initials: "+a1+" "+b1);
System.out.println("Encrypted Initials: "+c+" "+d);
}
}
Any thoughts?
I'm struggling with how I'm supposed to validate the inputs to only
allow one character, and not something such as a number or symbol
You can use isAlphabetic() method
Javadoc:
Determines if the specified character (Unicode code point) is an
alphabet. A character is considered to be alphabetic if its general
category type, provided by getType(codePoint), is any of the
following:
UPPERCASE_LETTER
LOWERCASE_LETTER
TITLECASE_LETTER
MODIFIER_LETTER
OTHER_LETTER
LETTER_NUMBER
or it has contributory
property Other_Alphabetic as defined by the Unicode Standard.
private static boolean isValidChar(char ch) {
return Character.isAlphabetic(ch);
}
and then exit the program if such an error arises
For example
if (!isValidChar(a))
System.exit(-1);
This is a program to read an integer:
public static void main(String argv[]) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(x);
}
But if I enter an input like this: 000114 it will be read like 114.How to read integer starts with zeroes?
Zeros are ignored at the start of an int. If you need the zeros to be displayed, store the number as a String instead. If you need to use it for calculations later, you can convert it to an int using Integer.parseInt(), so your code should look like this:
String x = input.next();
System.out.println(x);
//if you need x to be an int
int xInt = Integer.parseInt(x);
Keep in mind that, in this example, xInt will lose the zeros.
Perhaps you should read the input as a string and not as an integer if you really need to have the leading zeroes.
That is the expected outcome when reading an int with leading 0s because 000114 isn't an int when represented like that.
If you need it to be 000114 then you should read it as a string.
Well i'm trying to get a String from user and change each letter to the String "enc" I have down here. So basically if the user input "hello" I want it to return back "xahhi". I am kind of lost and don't know what to do.
String userInput = input.nextLine();
String letters = "abcdefghijklmnopqrstuvwxyz";
String enc = "kngcadsxbvfhjtiumylzqropwe";
int stringLength = userInput.length();
for (int i = 0; i < stringLength; i++) {
if (userInput.charAt(i) == letters.charAt(i)) {
System.out.print(enc.charAt(i));
}
}
What you want to do is have a Map<Character,Character> where key will be correct Character that in the String and the value should be Character that is encoded.
Then you query the Map for the encoding an generate you encoded string.
Code should look like :
Map<Character,Character> myEncodingMap = new HashMap<Character,Character>();
StringBuilder sb = new StringBuilder();
for (Character ch : letters.toCharArray()) {
sb.append(myEncodingMap.get(ch)
}
System.out.print(sb.toString());
Here is one that might be a little simpler if you are just starting out in programming. I have explained what each line does in the code so take a look and try to understand and expand on it! Let me know what you think or if you have any questions.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray(); //Just takes the String and puts it into a array of chars
char[] enc = "kngcadsxbvfhjtiumylzqropwe".toCharArray();
Scanner scan = new Scanner(System.in); //Scanner for user input
System.out.println("enter phrase"); //prompts for user input
String input = scan.next(); //Takes user input and stores it in String input
for(int i = 0; i<input.length(); i++){
char temp = input.charAt(i); //Stores the first Character of the entered phrase in a variable called temp.
int tempNums = (new String(letters).indexOf(temp)); //takes the position in the first array of the first char entered and stores it.
System.out.print(new String(enc).charAt(tempNums)); //prints out the values of the first character according to the second array.
}
}
}
If you want to use String methods only, you're close. However, you need to use two methods from the String class to finish this: indexOf(char) and charAt(int).
indexOf(char) takes a character and returns the index of the first location it appears in the string. For example, if you have a string with contents Hello World, then str.indexOf('l') will return 2, which is the first index in the string that matches the given character.
charAt(int) takes an integer and returns the character in a string at the given index. For example, using the same string as above, calling str.charAt(4) will return 'o'.
Using these two methods can get you an index of one string which you can then use to reference the character of the other.
I'm not going to put the answer in your code (you should learn enough to be able to do it yourself), but I'll give you a skeleton of how I would do this using just the two methods above.
// The two strings used for encoding
String strNormal = "ABCDEF";
String strCode = "UVWXYZ";
// The example string that is input by the user
String input = "BED";
/*** NOTE: This only replaces the first letter of the input string ***/
// Get the first character of the input string
char originalChar = input.charAt(0);
// Get the index of of the corresponding character in the normal string
int searchIndex = strNormal.indexOf(originalChar);
// Get the corresponding character of the encoder string
char encodedChar = strCode.charAt(searchIndex);
// Print out the encoded letter
System.out.print(encodedChar);
Though this approach will work, there are some caveats. The biggest one is performance: Every time you call indexOf or charAt, Java loops through the entire string to find what you're looking for. This isn't a problem for small strings like you'll be dealing with, but imagine a string that's maybe 10,000 characters long... It's possible that you'd have to search every letter in that string 10,000 times! Not super efficient.
I am trying to convert character values to ASCII values in java.
Below is my code.
public class test {
public static void main(String[] args)
{
System.out.println("Enter the string to be converted");
Scanner input = new Scanner(System.in);
String str =input.nextLine();
char ch[]=str.toCharArray();//hello
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
input.close();
}
}
I want to get the string from the user, and store it in an array(which I a m doing it in ch[]) and for each element in array, I want to print its corresponding ASCII value.
But at line char ascii[i]=ch[i]; the interpreter is telling Type mismatch: cannot convert from char to char[].
Where is the problem ? as both of my character initialization are arrays, then why is it telling that its type mismatch ?
Note: I want the ascii variable to be stored as an array only.
You can't assign a char to a char array.
Change
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
to
for(int i =0;i<str.length();i++)
{
char ascii = ch[i];
System.out.println((int)ascii);
}
EDIT:
If you wish to store the output in an array, you should declare the array before the loop :
char[] ascii = new char[str.length()];
for(int i =0;i<str.length();i++)
{
ascii[i] = ch[i];
System.out.println((int)ascii[i]);
}
when you declare ascii[i], you are trying to initialize a character array, but you are assigning it ch[i], which is a single character. Hence you get the error:
Type mismatch: cannot convert from char to char[].
As Eran said above, changing ascii variable from char array to character will resolve the issue.
The problem goes like this:
If a is assigned the value 1, b=2,c=3,...z=26, check if a given string is a Super Ascii String or not. A string is said to be a Super Ascii String, if the number of times a character is repeated matches its value. The string must be only in lowercase letters
Eg. abbccc is super ascii because a=1,b=2,c=3. Similarly, bab, "bb a ccc"
This is my attempt in solving the problem
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class SuperAsciiNew
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
String input = in.nextLine();
char[] inputArray = input.replaceAll("\\s+","").toCharArray();
Arrays.sort(inputArray);
String customInput = new String(inputArray);
char currentChar = customInput.charAt(0);
int increment=0;
Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
char a='a';
boolean superascii = true;
for(int i=1;a<='z';i++,a++)
characterMap.put(new Character(a), new Integer(i));
while(increment<=customInput.length())
{
int nooftimes = customInput.lastIndexOf(currentChar) - customInput.indexOf(currentChar) + 1;
if(characterMap.get(currentChar) == nooftimes)
{
System.out.println("The character "+currentChar+" is repeated "+nooftimes);
increment += nooftimes;
currentChar = customInput.charAt(increment);
}
else
{
superascii = false;
break;
}
}
if(superascii == true)
System.out.println("The given string "+input+" is a Super Ascii string");
else
System.out.println("The given string "+input+" is not a Super Ascii string");
}
}
Here, first I am removing spaces (if any), sorting the string. Then, I find the first character in the string, what is its value and how many times is it repeated. If these two values are not equal then the loop is broken else, the number of times the character is repeated is incremented in increment variable and the next character is found.
The output I get for various test cases:
java SuperAsciiNew
Enter a string : abb ccc
The character a is repeated 1
The character b is repeated 2
The character c is repeated 3
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : bab
The character a is repeated 1
The character b is repeated 2
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : hello world
The given string hello world is not a Super Ascii string
When the string "hello world" is given, the output is generated without any exceptions. What is the issue here?
I have one more doubt in Java:
What is the difference between importing individual classes like java.util.Scanner and importing the package as whole java.util.*? Are there any performance issues? What I feel is, the second one might consume more memory while the first, the system has to search the appropriate class and include it. Am I right in my thinking?
You are checking for a character one too many times.
Use the following condition:
while(increment<=customInput.length()-1)
instead of:
while(increment<=customInput.length())
Edit: the reason you are not getting the error on "hello world" is because it fails before reaching that extra char, thus not throwing an exception.