JAVA语法

JAVA语法

(内容参考www.acwing.com学习平台)

1. 基本语法

1.1 内置数据类型

变量 字节数 举例
byte 1 123(-128~127)
short 2 12345(-255~254)
int 4 123456789(-2e31~2e31-1)
long 8 1234123123L
float 4 1.2F
double 8 1.2 1.2D
Boolean 1 true;false
char 2 ‘A’

1.2 常量

使用final修饰;

final int N = 123;

1.3 类型转换

  • 显式转换(从高精度转换为低精度):int s = (int)1.33333
  • 隐式转换(从低精度转换为高精度):double y = 4 * 1.1 ;
1.4 表达式
int a = 1, b = 2, c = 3;
int d = (a + b) * c;
d ++;

1.5 输入

方式一:效率较低,输入规模小的时候使用。

Scanner sc = new Scanner(System.in);
String str = sc.next(); //读入下一个字符
int x = sc.nextInt(); //读入下一个整数
float y = sc.nextFloat(); //读入下一个单精度浮点数
double z = sc.nextDouble(); //读入下一个双精度浮点数
String line = sc.nextLine(); //读如下一行

方式二:效率较高,输入规模大时使用,注意需要抛异常。

package com.jyk;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
   
    public static void main(String[] args) {
   
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        System.out.println(str);
    }
}

1.6 输出

方式一:效率较低,输入规模小的时候使用。

System.out.println("hello world"); //输出字符串,换行
        System.out.println(123); //输出整数,换行
        System.out.print(3.14159); //输出单精度浮点数
        System.out.printf("%.3f %04d", 3.14159, 3); //格式化输出,float与double都用%f输出

方式二:效率较高,输入规模大时使用,注意需要抛异常。

package com.jyk;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

public class Main {
   
    public static void main(String[] args) throws Exception {
   
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        bw.write("hello world");
        bw.flush(); //需要手动刷新缓冲区
    }
}

1.7 判断语句

与C++、Python一样

import java.util.Scanner;

public class Main {
   
    public static void main(String[] args) {
   
        Scanner sc = new Scanner(System.in);
        int year = sc.nextInt();
        if (year % 100 == 0) {
   
            if (year % 400 == 0)
                System.out.printf("%d是闰年\n", year);
            else
                System.out.printf("%d不是闰年\n", year);
        } else {
   
            if (year % 4 == 0)
                System.out.printf("%d是闰年\n", year);
            
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值