第一种输入+不换行输出
import java.util.Scanner;//使用Scanner必须要加,好比C语言的头文件
public class Text {
public static void main(String[] args){
//输入
Scanner sc = new Scanner(System.in);
//第一种写法
int a = sc.nextInt();
byte b = sc.nextByte();
short c = sc.nextShort();
long d = sc.nextLong();
double e = sc.nextDouble();
float f = sc.nextFloat();
//字符输入
String g = sc.next();
String name = sc.next();
String name1 = sc.nextLine();
//不换行输出 d e f 输出加了空格
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d + " ");
System.out.print(e + " ");
System.out.print(f + " ");
//字符串输出
System.out.println(g);//这里换一下行
System.out.print(name);
System.out.print(name1);
}
}
//输入:1 2 3 4 5.12 6.123 abcd 你好 你好呀
//执行结果
1234 5.12 6.123 abcd
你好
你好呀
截图
第二种写法+换行输出
import java.util.Scanner;
public class Text {
public static void main(String[] args){
//第二种写法
Scanner scanner = new Scanner(System.in);
int a1;
byte b1;
short c1;
long d1;
double e1;
float f1;
a1 = scanner.nextInt();
b1 = scanner.nextByte();
c1 = scanner.nextShort();
d1 = scanner.nextLong();
e1 = scanner.nextDouble();
f1 = scanner.nextFloat();
//换行输出
System.out.println(a1);
System.out.println(b1);
System.out.println(c1);
System.out.println(d1);
System.out.println(e1);
System.out.println(f1);
}
}
//输入:1 2 3 4 5.12 6.123
//执行结果
1
2
3
4
5.12
6.123
截图
数组输入输出
一维数组
import java.util.Arrays;
import java.util.Scanner;
public class Text {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//一维数组
int[] arr = new int[3]; //未初始化
int[] arr1 = {1,2,3}; //赋初值
int[] arr2 = new int[]{1,2,3}; //赋初值后不用再for循环输入
//for循环输入输出
int i = 0;
for(i = 0; i < 3; i++)
{
arr[i] = sc.nextInt();
System.out.println(arr[i]);
}
System.out.println("====================");
//这也是打印数组的一种
for(int x: arr){
System.out.println(x);
}
System.out.println("====================");
//第三种输出
System.out.println(Arrays.toString(arr));//开头引import java.util.Arrays;
}
}
截图
二维数组
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
//第一种方式
int[][] arr1 = {{1,2,3},{4,5,6}};
//第二种方式 默认值是0
int[][] arr2 = new int[2][3];
//第三种方式 可以不给列的长度,但是一定要给行
int[][] arr3 = new int[2][];
//第四种
int[][] arr4 = new int[][] {{1,2,3},{4,5,6}};
//for循环打印
for(int i = 0; i < arr1.length; i++) { //arr.length = 2
for(int j = 0; j < arr1[i].length; j++) { // arr[i].length = 3
System.out.print(arr1[i][j] + " ");
}
System.out.println(); //打印一行就换行
}
System.out.println("========================");
//for-each打印
for (int[] arr : arr1) {
for (int x : arr) {
System.out.print(x + " ");
}
System.out.println();
}
System.out.println("========================");
//toString打印
String ret = Arrays.deepToString(arr1);
System.out.println(ret);
}
}