search
HomeJavajavaTutorialLet'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.

Let's talk about the input and output of common data types in Java

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();//</span></strong>##           System.out.println((int)ch);

}}

Note: Need to be used with IOException exception. In , 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 is int type and needs to be cast to char type.

1.2 Example

##2, int type

1.1 Simple int format input:

This refers to the situation where each line has only one int format input. For example, only one integer type is entered in each 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 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

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

//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

It should be noted that multiple groups of input single Characters need to be input in string format to convert to character type.

5. Array

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 

2.1 Convert array into string

Use 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 <p></p>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. <p></p>6. String

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'

1.2 Integer type, floating point type is converted into a 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 into 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

               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 <p> 结果如下:</p><p style="text-align:center;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/00e9bf358285249bafdd2b5ebe4307a6-13.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><br></p><h2 id="快速输入">7、快速输入</h2><p>        用Scanner进行输入是比较慢的,在这里介绍一个新的输入输出的函数。它们相比起来,优点是速度比较快,缺点可能就是太长了,打字很费劲。</p><pre class="brush:php;toolbar:false">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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool