键盘录入:
第一套体系:
nextInt();//接收整数
nextDouble();//接收小数
next();//接收字符串
特点:遇到空格,制表符,回车就停止接收
第二套体系:
nextLine();//接收字符串
特点:可以接收空格,制表符,遇到回车才停止接收
注:键盘录入的两套体系不能混用
混用弊端:先用nextInt();再用nextLine ();会导致下面的nextLine()接收不到数据
练习:
定义数组存储3部汽车对象。
汽车的属性:品牌,价格,颜色。
创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组当中。
代码如下:
package test;
public class Test {
private String brand;
private int price;
private String color;
public Test() {
}
public Test(String brand, int price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
/**
* 获取
* @return brand
*/
public String getBrand() {
return brand;
}
/**
* 设置
* @param brand
*/
public void setBrand(String brand) {
this.brand = brand;
}
/**
* 获取
* @return price
*/
public int getPrice() {
return price;
}
/**
* 设置
* @param price
*/
public void setPrice(int price) {
this.price = price;
}
/**
* 获取
* @return color
*/
public String getColor() {
return color;
}
/**
* 设置
* @param color
*/
public void setColor(String color) {
this.color = color;
}
public String toString() {
return "Test{brand = " + brand + ", price = " + price + ", color = " + color + "}";
}
}
package test;
import java.util.Scanner;
public class carTest {
public static void main(String[] args) {
//1.创建一个数组来存三个汽车对象
Test[] arr=new Test[3];
//2.创建汽车对象,数据来自键盘录入
Scanner sc=new Scanner(System.in) ;
for (int i = 0; i < arr.length; i++) {
//创建汽车对象
Test c=new Test();
//录入品牌
System.out.println("请输入汽车的品牌");
String brand=sc.next();
c.setBrand(brand);
//录入价格
System.out.println("请输入汽车的价格");
int price = sc.nextInt();
c.setPrice(price);
//录入颜色
System.out.println("请输入汽车的颜色");
String color=sc.next() ;
c.setColor(color) ;
arr[i]=c;
}
//3.遍历数组
for (int i = 0; i < arr.length; i++) {
Test car = arr[i];
System.out.println(car.getBrand() +","+car.getPrice() +","+car.getColor() );
}
}
}