Home  >  Article  >  Java  >  How to enter statements in java

How to enter statements in java

coldplay.xixi
coldplay.xixiOriginal
2020-10-23 15:15:0556550browse

How to input statements in java: 1. Enter a single character [char c=(char)System.in.read()]; 2. Enter an integer or string [int a=cin.nextInt()] ;3. You can use the BufferedReader class for input.

How to enter statements in java

How to input statements in java:

If you want to input, please add two packages

import java.util.*;
import java.io.*;

Please see the following example for inputting a single character

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args)throws IOException{
        char c=(char)System.in.read();
        System.out.println(c);
    }
}

Enter an integer or character (string)

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args)throws IOException{
        Scanner cin=new Scanner(System.in);
         
        int a=cin.nextInt();//输入一个整数
        System.out.println(a);
         
        double b=cin.nextDouble();//输入一个双精度的浮点数
        System.out.println(b);
         
        String str=cin.next();//输入一个单词,遇到分号则输入终止
        System.out.println(str);
         
        String str2=cin.nextLine();//输入一行,中间可有多个空格
        System.out.println(str2);
    }
}

You can also use the BufferedReader class to input

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
        String str=cin.readLine();//输入一行
        System.out.println(str);
         
        String str2=cin.readLine();
        int a=Integer.parseInt(str2);//将str2转换为int,并复制给a
        System.out.println(a);
         
        String str3=cin.readLine();
        double b=Double.parseDouble(str3);//将str3转换为double,并复制给b
        System.out.println(b);
    }
}

Related free learning recommendations: java basics

The above is the detailed content of How to enter statements in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn