1.创建引用类型
Scanner sc = new Scanner(System.in);
2.Scanner类的使用
导入包,new,使用方法调用
import java.util.Scanner;
public class demo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();//接收int类型
String name = sc.next();//接收字符串
System.out.println(name);
System.out.println(i);
}
}
3.Random随机数的使用1
import java.util.Random;
public class demo{
public static void main(String[] args){
Random rua = new Random();
System.out.println(rua.nextDouble());
//产生1-100的随机数 rua(100)是产生0-99的数 加1后1-100
int x = rua(100)+1;
System.out.println(x);
}
}
4.Random随机数的使用2
产生的是伪随机数,计算机中都是伪随机数.
5.if语句的第一种
public class demo{
public static void main(String[] args){
int x = 6;
if(x>5){
System.out.println("i大于5");
}
}
}
6.if语句的第二种
public class demo{
public static void main(String[] args){
int score = 100;
if(score==100){
System.out.println("带小明出去玩");
}else{
System.out.println("没有考到100分不能出去玩");
}
}
}
7.if语句的第三种
public class demo{
public static void main(String[] args){
int score = 70;
if(score>90){
System.out.println("优秀");
}else if(score>75){
System.out.println("良好");
}
else if(score>60){
System.out.println("及格");
}else{
System.out.println("你可以需要努力点!");
}
//也可以通过if来执行,但是效率比上面的低,因为此做法每个if都会判断一次
if(){
}
if(){
}
if(){
}
}
}
8.if和三元之间的转换
判断条件多,使用if,三元中必须要有结果,优先使用三元.
9.while循环
public class demo{
public static void main(String[] args){
int i = 1;
//输出1-4整数
while(i<5){
System.out.println(i);
i++
}
}
}
10.for循环1
for(初始化变量;循环条件;增量){
循环体
}
11.for循环2
for循环的执行顺序,先是初始化变量,接着是判断条件,如果是假那么程序直接退出,如果是真那么就直接执行循环体,然后增量,然后判断,然后循环体这样重复.
12.for循环3
public class demo{
public static void main(String[] args){
int sum = 0;
for(int i=1;i<101;i++){
sum+=i;
}
System.out.println(sum);
}
}
13.do-while循环
do{
循环体
}while(条件);
先无条件执行一次.
14.死循环
public class demo{
public static void main(String[] args){
while(true){
}
//无法访问的语句,因为上面是死循环
for(;;){
System.out.println("1");
}
}
}
15.嵌套for循环1
主要是两个for的嵌套,先执行外面的for,满足条件进入里面的for,知道里面的for循环完成后执行增量,接着如果再满足,继续执行里面的for
16.嵌套for循环2
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<9;i++){
for(int j=0;j<i+1;j++){
System.out.print("*");
}
System.out.println();
}
}
}
17.break语句
结束循环的,也可以使用相当于别名的来结束外循环
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
a:for(int i=0;i<9;i++){
for(int j=0;j<i+1;j++){
if(j==0){
break a;
}
}
System.out.println("11111");
}
}
}
18.continue
在循环中,终止本次循环,开始下一次循环。
19.猜数字游戏
1-100的随机数生成是答案,使用键盘录入来判断是否正确,并且提示大了还是小了,直到猜对。
import java.util.Random;
import java.util.Scanner;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Random ran = new Random();
Scanner sc = new Scanner(System.in);
int ans = ran.nextInt(100)+1;
while(true){
int x = sc.nextInt();
if(x>ans){
System.out.println("数大了");
}else if(x<ans){
System.out.println("数小了");
}else if(x==ans){
System.out.println("恭喜你,答对了!");
break;
}
}
}
}