Input and output of common data types in Java

        After learning C language and switching to Java, the first feeling is that Java's writing method is very complicated, and at the same time, it is not as convenient as C language in the input and output of commonly used data types. In the C language, most formats can be easily input with the scanf function, but not in Java. There is no statement similar to scanf in Java. This article combines my input and output habits and the record of doing questions, and makes a summary of these different types, such as integers, which are integers but separated by parameters. The main classes in the following description are all Main classes, and we use Scanner for input. There may be multiple methods for each input or output, and I only wrote a relatively simple way of writing.

1. Char type

        The char type mentioned here refers to the case where only one character is input.

 1.1 Input format:

import java.io.IOException;//导入包

public class Main {

    public static void main(String[] args) throws IOException {

        char ch = (char)System.in.read();//<1>

        System.out.println((int)ch);

    }

}

Description: It needs to be used with IOException. In <1>, System.in is input from the standard input stream (the most common is the keyboard), and the rand() method is to read the input content from this stream. The input result of <1> is int type and needs to be cast to char type.

1.2 Examples

2, int type

1.1 Simple int format input:

        This refers to the case where there is only one input in int format per line. For example, the case where only one integer is entered per line.

import java.util.Scanner;

public class Main {     public static void main(String[] args) {         Scanner scan = new Scanner(System.in);         int num = scan.nextInt();         System.out.println(num);     } }

        




 1.2 Examples

Remarks: Long num is required, otherwise, the result will be inaccurate when the num is too large.

2.1 Input in int format with spaces:

        Something like 23 34 format. There is a space between two numbers. At this time, using int input alone cannot solve the problem. Of course, you can use two scan.nextInt() consecutively to input. However, we can also at this time, we need to change the angle. We regard 23 34 as a string as a whole, and then divide it at the space to divide it into two strings of 23 and 34, and convert these two strings into integers. Please refer to the official help manual for the split() method.

import java.util.Scanner ;

public class Main {     public static void main(String[] args) {


        Scanner scan = new Scanner(System.in);
        String[] str = scan.nextLine().split("[ ]");//Divided into several pieces, there are several string arrays, here are two pieces of
        int a = Integer.parseInt (str[0]);
        int b = Integer.parseInt(str[1]);//etc...
        System.out.println(a + " " + b);
    }
}

 2.2 Examples

 

3.1 Input of complex int format

        Similar to input a=3, b=2, the method is the same as that described in 2.1. Here we go straight to the example.

3.2 Examples

The input of long type and int type is similar, and will not be repeated. 

3、double型

        In Java, double type should be used more instead of float type.

        The main thing about floating-point is its formatted output, such as a format that retains two decimal places. In Java, there is a printf method similar to the C language, and we can also use the format() method in String to achieve 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); 
     }
}

//printf format output:

//System.out.printf("%2f", num);

1.2 Examples

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 the 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 an easy way:

while(scan.hasNext()) 

1.2 Examples

 It should be noted that when multiple groups of single characters are input, they need to be input in string format to convert them to character types.

  

5. Array

        Input is similar to that in C language. However, it should be noted that for input such as strings, in C language, it is a pointer type. In Java, it has its own special string type. You cannot input each character in a loop without learning pointers like in C language. make up 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] + " ");
       }
  }
}

2.1 Convert array to string

        Just use the toString() method in Arrays. 

import java.util.Scanner;

import java.util.Arrays;

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();
       }
       System.out.println(Arrays.toString(arr));
   }
}

Enter 1, 2, 3 and you will see [1,2,3]. Sometimes the format of OJ questions is 1 2 3. [1,2,3] This format can also be passed.

6. String

        Since most of the input is converted to string type. Therefore, for strings, there are many operations that need to be converted, such as converting the split strings into integers, floating-point types, arrays, and so on.

1.1 Converting strings to integers, floating-point types (take integers as an example)

int a = Integer.parseInt (str[0]);//Assume str[0] is a character '1' after division

1.2 Integer, floating point conversion to string

int num = 10;

// method 1

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 to character array

 import java.util.Scanner;

import java.util.Arrays;

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 Convert character array to string

// method 1

new String(arr);

//method 2

String.copyValueOf(arr); 

3 Examples

Description: Write a function that inputs a string and implements the inversion of the string. code show as below:

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

 The result is as follows:

7. Quick input

        Using Scanner for input is relatively slow, here is a new input and output function. Compared with them, the advantage is that the speed is relatively fast, and the disadvantage may be that it is too long and typing is very laborious.

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

8. Write at the end

        These inputs are common. The more you write the code, the better you will master them.

Guess you like

Origin blog.csdn.net/Naion/article/details/122020669