温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中String、Char与Int之间的相互转换

发布时间:2021-09-16 17:10:26 来源:亿速云 阅读:128 作者:chen 栏目:编程语言

这篇文章主要讲解了“Java中String、Char与Int之间的相互转换”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java中String、Char与Int之间的相互转换”吧!

1.从终端输入的方式

Scanner类的使用方法:

Scanner scanner = new Scanner(System.in);

从终端获取输入流,输入流传入Scanner初始化对象时,作为参数传递进去。

Scanner类的重要几个方法:

next方法(读取一个字符)

1、一定要读取到有效字符后才可以结束输入(要是什么都不输入,则程序不结束)

2、对输入的有效字符之前遇到的空白,next方法会自动将其去掉。只有输入有效字符后才将其后面的输入的空白作为分隔符或者结束符。

next方法补鞥呢得到带有空格的字符串。

public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (sc.hasNext()){String next = sc.next();System.out.println(next);}}

nextLine方法(读取一行字符串)

1、以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。

2、可以获得空格。

public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (sc.hasNextLine()){String next = sc.nextLine();System.out.println(next);}}

nextInt读取一个整数。有时候可以直接在终端获取一个整数,不需要在将String转换为int。这样可以减少程序的运行时间。

2.String与Char

String转Char[]:利用toCharArray()

Scanner sc = new Scanner(System.in);String line = sc.nextLine();char[] chars = line.toCharArray();

String转单个插入字符:利用charAt()

Scanner sc = new Scanner(System.in);String line = sc.nextLine();char charAt = line.charAt(2);

3.String与int

int转化为String:利用valueOf()

int n = 10;String s = String.valueOf(10);System.out.println(s);

String转int:利用Integer.parseInt(s);

Scanner sc = new Scanner(System.in);String line = sc.nextLine();int i = Integer.parseInt(line);System.out.println(i);

4.输入的格式

例如:

5,15 2,10

import java.util.Scanner;/*** @author zhoujian123@hotmail.com 2018/8/24 19:27*/public class ScannerTest {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String line = sc.nextLine();String[] split = line.split(" ");for (int i = 0; i < split.length; i++) {String s = split[i];int i1 = Integer.parseInt(s.split(",")[0]);int i2 = Integer.parseInt(s.split(",")[1]);System.out.println(i1+" "+i2);}}}

感谢各位的阅读,以上就是“Java中String、Char与Int之间的相互转换”的内容了,经过本文的学习后,相信大家对Java中String、Char与Int之间的相互转换这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI