练习一
编写类A01,定义方法max,实现求某个double数组的最大值,并返回
public class Homework01 {
public static void main(String[] args) {
/* 编写类A01,定义方法max,实现求某个double数组的最大值,并返回
思路
1.先创建方法max接收double数组
2.使用for循环遍历数组
3.定义一个变量保存元素,进行比较
4.返回double值
*/
A01 a = new A01();
double[] arr = {30.1, 5.1, 6, 91.4, 500.6};
Double res = a.max(arr);
if(res != null) {
System.out.println("double数组的最大值=" + a.max(arr));
}else {
System.out.println("arr输入有误,不能为null或者{}");
}
}
}
class A01 {
public Double max(double[] arr) {
//保证arr至少有一个元素
//先判断是否为空 在判断arr是否正确
if(arr != null && arr.length > 0) {
double max = arr[0];
for(int i = 1; i < arr.length; i++) {
if(max < arr[i]) {
max = arr[i];
}
}
return max;
}else {
return null;
}
}
}
练习二
编写类A02,定义方法find,实现查找某字符串数组中的元素查找,并返回索引
如果找不到,返回-1.
import java.util.Scanner;
public class Homework02 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
/* 编写类A02,定义方法find,实现查找某字符串数组中的元素查找,并返回索引
如果找不到,返回-1.
思路
1.先创建方法find接收字符串数组
2.使用for循环遍历数组,查找
3.定义一个变量,判断是否找到,没有找到就返回-1
*/
System.out.println("请输入一个名称");
String name = myScanner.next();
String[] arr = {"白眉鹰王", "金毛狮王", "紫衫龙王", "青翼蝠王"};
String find = name;
A02 a = new A02();
if(a.find(find, arr) != -1) {
System.out.println("找到了,下标值为" + a.find(find, arr));
}else {
System.out.println("没找到对应的名称");
}
}
}
class A02 {
public int find(String find, String[] arr) {
//遍历数组查找
for(int i = 0; i < arr.length; i++) {
if(find.equals(arr[i])) {
return i;
}
}
return -1;
}
}
练习三
编写类Book,定义方法updatePrice,实现更改某本书的价格
具体:如果价格>150 则更改为150 如果价格>100 则更改为100,否则不变
import java.util.Scanner;
public class Homework03 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
/* 编写类Book,定义方法updatePrice,实现更改某本书的价格
具体:如果价格>150 则更改为150 如果价格>100 则更改为100,否则不变
思路
1.先创建方法updatePrice接收 需要更改的价格 和 书本
2.使用if进行判断如果价格>150 则更改为150
如果价格>100 则更改为100,否则不变
*/
System.out.println("请输入需要修改的价格");
int price = myScanner.nextInt();
Book b = new Book("西游记", price);
b.info();//原书本信息
System.out.println("===更改价格后===");
b.updatePrice();//调用方法更改书本价格
b.info();
}
}
class Book {
String name;
double price;
//构造器接收书本信息
public Book(String name, double price) {
this.name = name;
this.price = price;
}
//更改书本价格
public void updatePrice() {