Reputation: 3471
I'm trying to my first program text to ASCII converter, but I have some problems, it's explained inside the code:
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii = ('convert'/1); // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
Upvotes: 1
Views: 3458
Reputation: 109557
(Maybe use Scanner.nextLine()
.)
import java.text.Normalizer;
import java.text.Normalizer.Form;
String ascii = Normalizer.normalize(myChars, Form.NFKD)
.replaceAll("\\P{ASCII}", "");
This splits all accented chars like ĉ
into c
and a zero length ^
. And then all non-ascii (capital P = non-P) is removed.
Upvotes: 2
Reputation: 5712
String x = "text"; // your scan text
for(int i =0; i< x.getLength(); x++){
System.out.println((int)x.charAt(i)); // A = 65, B = 66...etc...
}
Upvotes: 2
Reputation:
This code will work
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii= (int)convert; // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
Upvotes: 0
Reputation: 181
did you missed type casting the character to integer? try this:
int ascii = (int) convert;
Upvotes: -1
Reputation: 1695
Replace this line
"int ascii = ('convert'/1);"
by
int ascii= (int)convert;
This should work.
Upvotes: 0
Reputation: 4121
Try this:
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
char[] charArray = myChars.toCharArray();
for (char character : charArray) {
System.out.println((int)character);
}
scanner.close();
}
This converts the string to a char array and then prints out the string representation of each character.
Upvotes: 0