一、java的安装
下载JDK,安装然后添加环境变量jdk\bin
二、用记事本写第一个java程序
1、新建Test.java,输入代码
public class Test{
public static void main(String[] args){
int number = 23;
System.out.println(number); //变量申明并赋值才能使用
System.out.println(number);
/*
多行注释
多行注释
*/
}
}
编译: javac Test.java 然后产生Test.class二进制文件
运行: java Test
变量命名:以字母、下划线、$开头
变量,取余
public class Test{
public static void main(String[] args){
int price=499;
double weight=12.4;
String type="sfddvfv";
System.out.println(price);
System.out.println(weight);
System.out.println("字符串:"+weight); //用+连接字符串和数值
int a=46;
int result=a%7; //取余
}
}
数据类型自动转换:int + double = double; char + string = string
接收用户输入Scanner类
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入姓名:");
String name = in.next();
System.out.println("请输入年龄:");
int age = in.nextInt();
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
}
}
数值交换
public class Test{
public static void main(String[] args){
int a = 45;
int b = 78;
int temp = a;
a = b;
b = temp;
System.out.println("a的值为:" + a);
System.out.println("b的值为:" + b);
}
}
boolean类型
public class Test{
public static void main(String[] args){
int a = 2;
int b = 2;
boolean flag;
flag = (a==b);
System.out.println(flag); //ture
}
}
逻辑运算符: && || !
if.....else if.....
import java.util.*;
public class Test{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = in.nextInt();
if (score >= 90){
System.out.println("优秀");
}else if(score >= 80){
System.out.println("良好");
}else if(score >= 60){
System.out.println("中等");
}else{
System.out.println("差");
}
System.out.println("测试");
}
}
switch
import java.util.*;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入名次:");
int mingci = input.nextInt();
switch(mingci) {
case 1:
System.out.println("第一名");
break;
case 2:
System.out.println("第二名");
break;
case 3:
System.out.println("第三名");
break;
default:
System.out.println("逐出师门");
}
}
}
判断闰年,平年
import java.util.*;
public class Test{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入年份:");
int year= in.nextInt();
if( year%4==0 && year%100!=0 || year % 400 ==0){
System.out.println(year + "是一个闰年");
}else{
System.out.println(year + "是一个平年");
}
}
}
产生随机数
import java.util.Random;
public class Test{
public static void main(String[] args){
Random x = new Random();
int number = x.nextInt(10); //0~9
System.out.println("随机数为:" + number);
int a = (int)(Math.random()*10);
System.out.println("随机数为:" + a);
}
}