温馨提示×

温馨提示×

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

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

Java中String、Char和Int之间相互转换的示例分析

发布时间:2021-07-24 09:35:25 来源:亿速云 阅读:144 作者:小新 栏目:编程语言

这篇文章主要介绍Java中String、Char和Int之间相互转换的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1.从终端输入的方式

Scanner类的使用方法:

Scanner scanner = new Scanner(System.in);

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

Java中String、Char和Int之间相互转换的示例分析

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

Java中String、Char和Int之间相互转换的示例分析

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

Java中String、Char和Int之间相互转换的示例分析

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

2.String与Char

String转Char[]:利用toCharArray()

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

Java中String、Char和Int之间相互转换的示例分析

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

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

Java中String、Char和Int之间相互转换的示例分析

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

Java中String、Char和Int之间相互转换的示例分析

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