如何在Java中将字符串转换为ASCII值? [英] How to cast string to ascii value in java?

查看:106
本文介绍了如何在Java中将字符串转换为ASCII值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有新任务,并且由于我是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...

我想从人那里获得诸如姓名之类的输入并将其更改为数字(int)...这表示不可能从字符串转换为int ... !!

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

}

推荐答案

您可以尝试以下方法:

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

这篇关于如何在Java中将字符串转换为ASCII值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆