Let's talk about the input and output of common data types in Java
This article brings you relevant knowledge about java, which mainly introduces the input and output related issues of common data types. Let’s take a look at how to solve these problems through examples. Questions about input and output of commonly used data types. I hope it will be helpful to everyone.
Recommended study: "java tutorial"
After learning C language and switching to Java, the first thing I feel is Java The writing method is very complicated, and at the same time, the input and output of commonly used data types are not as convenient as C language. In C language, using the scanf function can easily input most formats, but not in Java. There is no statement similar to scanf in Java.
This article combines my input and output habits and records of doing questions to make a summary of these different types, such as integers, integers but separated parameters... In the following instructions, the main classes are all Main classes, and we use Scanner for input. Each input or output may have multiple methods, and I only wrote the simpler method.
1. Char type
The char type mentioned here refers to the case where only one character is entered.
1.1 Input format:
import
<span style="background-color:#ed7976;">java.io.IOException</span>;//Import Package
public
class
Main {<!-- -->
public
static
void
main(String[] args)
<span style="background-color:#ed7976;">throws</span>
<span style="background-color:#ed7976;">IOException</span> {<!-- -->
#ch = (<strong><span style="color:#0d0016;">char)System.in.read();//<1></span></strong>
##System.out.println((
int)ch);
}
}
1.2 Example
Note: Need to be used with IOException exception. In <1>, System.in is input from the standard input stream (most commonly the keyboard), and the rand() method reads the input content from this stream. The input result of <1> is int type and needs to be cast to char type.
##2, int type
1.1 Simple int format input:
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();System.out.println(num);}
}
1.2 Example
Note: It needs to be Long num, otherwise the result will be inaccurate when num is very large.
2.1 Input int format with spaces:
Similar to the format of 23 34. There is a space between the two numbers. At this time, using int input alone cannot solve the problem. Of course, you can use two scan.nextInt() consecutively for input. However, we still need to change our perspective at this time. We treat 23 34 as a whole as a string, and then split it at the space into two strings of 23 and 34, and then convert these two strings into integers. Please check the official help manual for the split() method.
import
;
Scanner scan = new Scanner(System.in);
String[] str = scan.nextLine().split("[ ]");//Divided into several blocks, there are several characters String array, here are two pieces
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);//etc. ...
System.out.println(a " " b);
}
}
2.2 Example
3.1 Input of complex int format
Similar to inputting a=3, b=2, the method is the same as explained in 2.1. Here we go directly to the example.
3.2 Give an example
The input of long type and int type are similar and will not be described again.
3. Double type
In Java, the double type should be used more often than the float type.
The floating point type is mainly its formatted output, such as retaining two decimal places. In Java, there is a printf method similar to that in C language, and we can also use the format() method in String to implement it.
1.1 double retains two-digit format output
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double num = scan.nextDouble(); String a = String.format("%.2f", num); System.out.println(a); } }Copy after login//printf format output:
// System.out.printf("/", num);
1.2 Example
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.nextLine(); String[] num = str.split("[;,]"); String a = String.format("%.2f", Double.parseDouble((num[1]))); String b = String.format("%.2f", Double.parseDouble((num[2]))); String c = String.format("%.2f", Double.parseDouble((num[3]))); System.out.println("The each subject score of No. " + num[0] + " is " + a + ", " + b + ", " + c + "."); } }
4, enter
# multiple times ##1.1 Input format In C language, there are two simpler ways to loop multiple inputs:while(scanf("%d", &n) != EOF)## while(~scanf("%d", &n) )
In Java, there is also a simple way:while(scan.hasNext())
1.2 Example
The input is similar to that in C language. However, it should be noted that input such as strings is a pointer type in C language. In Java, it has its own string type. It cannot be like C language, where you can input each character in a loop before learning pointers. form a string.
1.1 Array input format:
import java.util.Scanner;public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[3];//输入3个
for(int i = 0; i < arr.length; i++) {
arr[i] = scan.nextInt();
}
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Copy after login
public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] arr = new int[3];//输入3个 for(int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
2.1 Convert array into string Use Just use the toString() method in Arrays.import java.util.Scanner;import java.util.Arrays;
Enter 1, 2, 3 and you will see the result [1,2,3]. Sometimes the format of OJ questions is 1 2 3. The format [1,2,3] can also pass. 6. Stringpublic class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] arr = new int[3];//输入3个 for(int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } System.out.println(Arrays.toString(arr)); } }Copy after login
Since most input is converted to string type. Therefore, for strings, there are many conversion operations required, such as converting the split string into integers, floating point types, arrays, etc.
1.1 Convert string to integer or floating point type (taking integer as an example)
int a =Integer.parseInt
(str[0] );//Assume that str[0] after splitting is a character '1'int num = 10 ;// Method 11.2 Integer type, floating point type is converted into a string
import java.util.Scanner;import java.util.Arrays;String str1 = num "";//"" represents an empty string, which is different from null in Java
// Method 2
String str2 = String.valueOf(num);
2.1 Convert string into character array
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
2.2 字符数组转换成字符串
// 方法1
new String(arr);
//方法2
String.copyValueOf(arr);
3 举例说明
描述:写一个函数,输入一个字符串,实现字符串的逆置。代码如下:
import java.util.Scanner; public class Main { public static String my_reverse(String str) { int left = 0; int right = str.length() - 1; char[] arr = str.toCharArray(); while(left < right) { char tmp = 0; tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; } return new String(arr); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.next(); String ret = my_reverse(str); System.out.println(ret); } }
结果如下:
7、快速输入
用Scanner进行输入是比较慢的,在这里介绍一个新的输入输出的函数。它们相比起来,优点是速度比较快,缺点可能就是太长了,打字很费劲。
import java.io.*; //省略了Main public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(bf.readLine()); System.out.println(a); double b = Double.parseDouble(bf.readLine()); System.out.println(b); char c = bf.readLine().charAt(0); System.out.println(c); char d = (char)bf.read();//都可以,但是这个不能和多组输入连用,原因是它保留了换行。 System.out.println(d); System.out.println("------"); String str = null; //多组输入 while((str = bf.readLine()) != null) { char ch = str.charAt(0);//其他的类似 System.out.println(ch); } }
推荐学习:《java学习教程》
The above is the detailed content of Let's talk about the input and output of common data types in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
