Hamed Fazilat Hamed Fazilat - 6 months ago 23
Java Question

How to cast string to ascii value in java?

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

}

Answer

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