Scanner
使用示例:
public class DemoSanner02 {
public static void main(String[] args) {
//创建一个扫描器的对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
if(scanner.hasNext()) {
//使用next接收
String str = scanner.next();//只接受空格前一个单词
System.out.println("输出的内容为:" +str);
}
//判断用户有没有输入字符串
if(scanner.hasNextLine()) {
//使用next接收
String str = scanner.nextLine();//接受一行单词
System.out.println("输出的内容为:" +str);
}
//凡是使用IO流的对象,用完必须关闭
scanner.close();
}
}
Scanner scanner = new Scanner(System.in);
//从键盘接收数据:
int i = 0;
float f = 0.0f;
System.out.println("请输入整数:");
if(scanner.hasNextInt()) {
i = scanner.nextInt();
System.out.println("整数数据:" + i);
}
else {
System.out.println("输入的不是整数数据!");
}
System.out.println("请输入数:");
if(scanner.hasNextFloat()) {
f = scanner.nextFloat();
System.out.println("小数数据:" + f);
}
else {
System.out.println("输入的不是小数数据!");
}
scanner.close();
public class ScannerPractice {
public static void main(String[] args) {
//输入多个数字,求和,遇到非数字退出系统
Scanner scanner = new Scanner(System.in);
//和
double sum = 0;
int num = 0;
while(scanner.hasNextDouble()) {
double x = scanner.nextDouble();
num += 1;
sum += x;
}
double avg = sum / num;
System.out.println("和是:"+sum);
System.out.println("平均值:"+avg);
scanner.close();
}
}
顺序、选择、循环结构:
package Sequence;
import java.util.Scanner;
public class demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
if (scanner.hasNextInt()) {
int score = scanner.nextInt();
if (score > 60) {
System.out.println("及格!");
}
else {
System.out.println("不及格!");
}
}
else if (scanner.hasNextDouble()) {
System.out.println("成绩不是整数!");
}
else {
System.out.println("不是数字");
}
scanner.close();
}
}
public class For {
public static void main(String[] args) {
int[] numbers = {10,20,30,40};
//格式1
for(int i = 0; i < 4; i++) {
System.out.println(numbers[i]);
}
//格式2
for(int x :numbers) {
System.out.println(x);
}
}
}
public class BreakContinue {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
if(i == 5) {
continue;
}
if (i == 7) {
break;
}
System.out.print(i);
}
}
}
package circulation;
public class While {
public static void main(String[] args) {
int i = 0;
int sum = 0;
//格式1
while(i <= 100) {
sum += i;
i += 1; //i++
}
//格式2
do {
sum += i;
i += 1;
}while(i <= 100);
System.out.println(sum);
}
}