Java中常见的函数及其使用示例
发布时间:2023-07-17 12:09:38
Java中常见的函数有很多,下面列举了一些常见的函数及其使用示例:
1. println函数:用于输出信息到控制台
System.out.println("Hello, world!");
2. scanf函数:用于从控制台读取输入信息
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Your name is " + name);
3. parseInt函数:用于将字符串转换为整数
String numStr = "123";
int num = Integer.parseInt(numStr);
System.out.println("The number is " + num);
4. toString函数:用于将对象转换为字符串形式
int num = 123;
String numStr = Integer.toString(num);
System.out.println("The number is " + numStr);
5. length函数:用于获取数组或字符串的长度
String str = "Hello, world!";
int length = str.length();
System.out.println("The length of the string is " + length);
6. substring函数:用于截取字符串的子串
String str = "Hello, world!";
String subStr = str.substring(7);
System.out.println("The substring is " + subStr);
7. Math类的函数:提供了一些常用的数学函数
int absNum = Math.abs(-123);
System.out.println("The absolute value is " + absNum);
double sqrtNum = Math.sqrt(25);
System.out.println("The square root is " + sqrtNum);
double randomNum = Math.random();
System.out.println("The random number is " + randomNum);
8. ArrayList类的函数:用于操作动态数组
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println("The size of the list is " + list.size());
String element = list.get(1);
System.out.println("The element at index 1 is " + element);
9. String类的函数:提供了一些字符串操作的函数
String str1 = "Hello";
String str2 = "World";
String concatStr = str1.concat(str2);
System.out.println("The concatenated string is " + concatStr);
boolean containsWorld = str1.contains("World");
System.out.println("The string contains 'World': " + containsWorld);
int index = str1.indexOf("e");
System.out.println("The index of 'e' is " + index);
以上是一些常见的函数及其使用示例,但这只是Java中的一小部分函数,Java作为一门功能强大的编程语言,提供了非常多的函数用于不同的需求。在编程中,需要根据具体情况选择合适的函数来解决问题。
