带有循环的Java文本到ASCII转换器

时间:2014-07-31 11:07:01

标签: java

我尝试将我的第一个程序文本转换为ASCII转换器,但是我遇到了一些问题,它在代码中进行了解释:

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

6 个答案:

答案 0 :(得分:2)

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...
}

答案 1 :(得分:2)

(也许使用Scanner.nextLine()。)

import java.text.Normalizer;
import java.text.Normalizer.Form;
String ascii = Normalizer.normalize(myChars, Form.NFKD)
        .replaceAll("\\P{ASCII}", "");

这会将所有重音字符ĉ分为c和零长^。然后删除所有非ascii(大写P =非P)。

答案 2 :(得分:0)

试试这个:

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

这会将字符串转换为char数组,然后打印出每个字符的字符串表示形式。

答案 3 :(得分:0)

替换此行

"int ascii = ('convert'/1);"

通过

  

int ascii =(int)convert;

这应该有效。

答案 4 :(得分:0)

此代码可以使用

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

答案 5 :(得分:-1)

你错过了将字符转换为整数的类型吗? 试试这个:

int ascii = (int) convert;