How to cast string to ascii value in java?

2019-06-11 06:37发布

问题:

I have new assignment and since I am new to JAVA I don't know how to make it work, I have searched this website frequently but all the solutions which were suggested didn't work out for me or I didn't use them properly, I would be grateful if someone helps me... the code below is the most simple solution I could find but still doesn't work...

I want to get inputs like names from people and change them to numbers (int)...it says it is not possible to cast from string to int ... !!

 package loveindex;
import java.util.Scanner;
//import java.math.BigInteger;

public class LoveIndex {

private static Scanner scan;

public static void main(String[] args) {
    scan = new Scanner(System.in);

    System.out.println("Testing Scanner, write something: ");
    String testi = scan.nextLine();
    System.out.println(testi);
    System.out.println("Testing Scanner, write something: ");
    String testi2 = scan.nextLine();
    System.out.println(testi2);

    int ascii = (int) testi;
    int ascii = (int) testi2;
  }

}

回答1:

You Can Try This:

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.println("Testing Scanner, write something: ");
    String testi = scan.nextLine();
    char[] ascii1 = testi.toCharArray();

    for(char ch:ascii1){
        System.out.println((int)ch+"  ");
    }


    System.out.println("Testing Scanner, write something: ");
    String testi2 = scan.nextLine();
    char[] ascii2 = testi2.toCharArray();

    for(char ch:ascii2){
        System.out.println((int)ch+"  ");
    }

  scan.close();
}


回答2:

Achieve the same in a concise way by employing Java 8's lambda function. From your comment (at the accepted answer) you need the sum of the characters at the end?

String str = "name";
int sum = str.chars().reduce(0, Integer::sum);


回答3:

You're attempting to assign a String to an int which the 2 of which are incompatible. You can get the ascii value of a single character

int ascii = testi.charAt(0);


回答4:

You cannot convert string to ascii like that. You can convert a character to ascii

int ascii = (int)some_char;


回答5:

First of all: Java doesn't use ASCII. It use Unicode (UTF-16, most of the time).

Second: You can make a function to convert your String characters to their Unicode representations, like this:

public static int[] convert(String str) {
    int[] result = new int[str.length()];
    for (int i = 0; i < str.length(); i++) {
        result[i] = str.charAt(i);
    }
    return result;
}


标签: java ascii