java学习

java 学习



前言

提示:图片均截至b站尚硅谷java基础添加链接描述


提示:以下是本篇文章正文内容,下面案例可供参考

一,1.快捷键

  1. Ctrl+z:撤销
  2. Alt+f4:关闭窗口
  3. shift+delete:永久删除
  4. windows+r:命令窗口
  5. alt+tab:切换窗口
  6. ctrl+shift+esc:任务管理器

2.Dos命令

  1. 盘符切换 D:回车
  2. .dir回车:查看当前目录下的所有文件
  3. cd/d:切换目录
  4. cls :清理屏幕
  5. ipconfig : 查看电脑ip
  6. md :创建目录
  7. rd :删除目录
  8. cd…:退回到上级目录
  9. cd\ : 退回到根目录
  10. del: 删除文件
  11. exit:退出dos命令行

二、java

(一).基础语法

1.helloworld

package newlearn.hello;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub main方法是程序的入口
		System.out.println("hello,world");

	}

}

注意:public只能加到与文件名相同的类上
System.out.println()换行
System.out.print()不换行

2.注释

1.单行注释://
2.多行注释:/* /
3.文档注释(java特有)/
* */
在这里插入图片描述在这里插入图片描述在这里插入图片描述

3.Java数据类型

1.基本数据类型:

(1)数值型:整数类型(byte(一个字节-128—127),shot(2个字节),int(4) ,long(8))
浮点类型(float(4),double(8)
(2)字符型(char
(3)布尔型(boolean

2.引用数据类型:

(1) 类(class
(2)接口(interface
(3)数组([]

class Variable{
	public static void main(String[] args){
	byte a=12;
	System.out.println(a);
	short b=128;
	int c=123;
	long d = 1234567L;//要写“l”或者“L”
	System.out.println(d);
	double e=123.1;
	System.out.println(e);
	float f=12.5F;//要写“f”或者“F”
	System.out.println(f);


	}	
}

编码GBK的不可映射字符解决办法
bian在这里插入图片描述

3.自动数据类型转换

byte short int long float double(当容量小的数据变量做运算时结果自动提升为容量大的数据变量)
当byte,char,short三种类型的变量做运算时,结果为int型

4.强制类型转换
class Variable{
	public static void main(String[] args){

	double a = 12.9;
	int b = (int)a;   //截断操作;
	System.out.println(b);
}
}
5.String
class StringTest{
	public static void main(String[] args){
	String a = "hello";
	System.out.println(a);
	int number = 10001;
	String numberstr = "学号:";
	String info  = numberstr  + number;
 	System.out.println(info);

}
}

Stringf可以做8种运算且运算只能是连接运算运算结果依然是String

在这里插入图片描述
在这里插入图片描述
-2是整形应该为int

6.标识符的命名规则(自己可以起名字的地方)
  1. 标识符应以字母、下划线或美元符开头,后面可以跟字母、下划线、美元符或数字。 标识符是大小写敏感的,长度没有限制。
  2. 在Java中,可以用作标识符的有26个英文字母(大写和小写)、数字、下划线和美元符号$,但不能以数字开头
  3. 类名的首字母必须大写,如果由多个单词组成,每个单词的首字母都要大写。
  4. 方法名一般以小写字母开头(构造方法是个例外),如果由多个单词组成,后面的单词的首字母要大写。 变量的命名规则和方法名相同。
  5. 注意,不能使用Java中的关键字作为标识符。
  6. Java语言有51个关键字,其中const和goto虽然被保留但未使用。你不能使用保留关键字来命名类、方法或变量。
  7. 数据类型、流程控制、修饰符、动作和保留字都是Java中的关键字。 总体上说,Java是大小写敏感的,即区分大小写。
7.标识符的命名规范

包名:xxxyyyzzz
类名,接口名:XxxYyyZzz
变量名,方法名:xxxYyyZzz
常量名:xxx_yyy_zzz

8.关键字

在这里插入图片描述

4.运算符

1.算数运算符

在这里插入图片描述

class AriTest
{
	public static void main(String[] args)
	{
		System.out.println("Hello World!");
		int num1 = 12;
		int num2 = 5;
		int result1 = num1 / num2;
		System.out.println(result1);//2
		
		double result2 = num1 / num2;
		System.out.println(result2);//2.0
			
		double result3 = num1 / num2 + 0.0;//2.0
		System.out.println(result3);

   		double result4 = num1 / (num2 + 0.0);//2.4
		System.out.println(result4);

		double result5 = (double)num1 / num2;//2.4
		System.out.println(result5);

		double result6 = (double)(num1 / num2);//2.0
		System.out.println(result6);
 	}

}

取模结果的符号与被模符号相同

前++(先+1,再运算),和后++的区别(先运算,后+1)

class AriTest1{
	public static void main (String[] args)
	{
	int a1 = 10;
	int b1 = ++a1;
	System.out.println("a1 = " + a1+",b1 = "+b1);
	
	int a2 = 10;
	int b2 = a2++;
	System.out.println("a2 = "+a2+",b2 = "+b2);
	}	
}

a1 = 11,b1 = 11
a2 = 11,b2 = 10

2.逻辑运算符
区别&与&&

相同点1.&与&&运算结果相同
相同点2.当符号左边是true是,二者都会执行符号右边的运算
不同点:当符号左边是false时,&继续执行符号右边的运算,&&不再执行

class LogicTest{
	public static void main(String[] args){
	boolean b1 = true;
	b1 = false;
	int num1 = 10;
	if(b1&(num1++>0)){
		System.out.println("我现在在北京");
}	else{
		System.out.println("我现在在南京");
}
	System.out.println("num1 = "+num1);//num1 = 11

	boolean b2 = true;
	b2 = false;
	int num2 = 10;
	if(b2 && (num2++ > 0)){
		System.out.println("我现在在北京");
}	else{
		System.out.println("我现在在南京");
}
	System.out.println("num2 = "+num2);//num2= 10
}
}

运行结果
在这里插入图片描述

区别|与||

相同点1.|与||运算结果相同
相同点2.当符号左边是false时,二者都会执行符号右边的运算
不同点:当符号左边是true时,|继续执行符号右边的运算,||不再执行

3.位运算符

在一定范围内<<向左移一位相当于*2,>>向右移一位相当于/2
& | ^
在这里插入图片描述

4.三元运算符

(条件表达式)?表达式1:表达式2

class SanYuanTest{
	public static void main(String[] args){
	int n1 = 12;
	int n2 = 30;
	int n3 = -43;                      //找三个数中最大的数
	int max1 = (n1 > n2)?n1:n2;
	int max2 = (max1 > n3)?max1:n3;
	System.out.println("三个数中最大值为:" + max2);	
}
}

5.流程控制

(1)if–else
练习一(三个数排序)
import java.util.Scanner;
class Text{
	public static void main(String[] args){

	Scanner scanner = new Scanner(System.in);

        System.out.println("请输入第一个数:");
	int a = scanner.nextInt();
	System.out.println("请输入第二个整数:");
	int b = scanner.nextInt();
	System.out.println("请输入第三个整数:");
	int c = scanner.nextInt();
       
	if(a>=b){
		if(c>=a) System.out.println(b+","+a+","+c);
		else if(c<=b) System.out.println(c+","+b+","+a);
                else System.out.println(b+","+c+","+a);
	}else{
		if(c>=b)System.out.println(a+","+b+","+c);
		else if(c<=a)System.out.println(c+","+a+","+b);
		else System.out.println(a+","+c+","+b);
		}
}
	
}
(1)switch-case
class SwitchCaseTest{
	public static void main(String[] args){
	int number = 2;
	switch(number){
	case 0:
		System.out.println("zero");
		break;
	case 1:
		System.out.println("one");
		break;
	case 2:
		System.out.println("two");
		break;
	case 3:
		System.out.println("three");
		break;
 	default:
		System.out.println("other");
	}	
}
}

6.使用Scanner从键盘输入

import java.util.Scanner;
class ScannerTest{
	public static void main(String[] args){
	Scanner scan = new Scanner(System.in);
	int num = scan.nextInt();
	System.out.println(num);	
}
}
import java.util.Scanner;
class ScannerTest{
	public static void main(String[] args){
	Scanner scan  = new Scanner(System.in);
		
	System.out.println("请输入你的姓名:");
	String name = scan.next();
	System.out.println(name);
	
	System.out.println("请输入你的芳龄:");
	int age = scan.nextInt();
	System.out.println(age);

	System.out.println("请输入你的体重:");
	double weight = scan.nextDouble();
	System.out.println(weight);

	System.out.println("你是否像中我了呢?");
	boolean islove = scan.nextBoolean();
	System.out.println(islove);
	
	System.out.println("请输入你的性别:");
	String gender = scan.next();
	char genderChar = gender.charAt(0);//获取索引为0位置的字符
	System.out.println(genderChar);
	 
}
}

6.循环结构

1.for循环
class Fortest{
	public static void main(String[] args){
	for(int i=1;i<=5;i++){
		System.out.println("Hello World!");	
	}
	}
}
练习1
class ForTest1
{
	public static void main(String[] args)
	{
		 for(int i = 1;i <= 150;i++){
			System.out.print(i+" ");
		if(i%3==0){
			System.out.print("foo ");
			}
		if(i%5==0){
			System.out.print("biz ");
			}
		if(i%7==0){
			System.out.print("baz ");
			}
		System.out.println();
		}
		
	}
}
练习2.找最大公约数和最小公倍数
import java.util.Scanner;
class ForTest{
	public static void main(String[] args){
	Scanner scan  = new Scanner(System.in);
	
	System.out.println("请输入第一个正整数:");
	int m = scan.nextInt();

	System.out.println("请输入第二个正整数:");
	int n = scan.nextInt();

	//获取最大公约数
	int min = (m<=n)?m:n;
	for(int i = min;i>=1;i--){
		if(m%i ==0&&n%i==0){
			System.out.println(i);
			break;
			}
		}
	//获取最小公倍数
	int max = (m>=n)?m:n;
	for(int i=max;i<=m*n;i++){
	if(i%m==0&&i%n==0){
			System.out.println(i);
 			break;	
			}
		}
	}
}
2.while循环
练习1
import java.util.Scanner;
//遍历100以内的所有的偶数
class WhileTest{
	public static void main(String [] args){
	int i= 1;
	while(i<=100){
	if(i%2==0){
		System.out.println(i);		
			}
		i++;
		}
	}
}
3.do-while循环
class DoWhileTest{
	public static void main(String[] args){
	int num = 1;
	do{
		if(num%2==0){
			System.out.println(num);
			}
		num++;
		}while(num <= 100);
	}	
}
forwhileTest
import java.util.Scanner;
class ForWhileTest{
	public static void main(String[] args){
	Scanner scan  = new Scanner(System.in);
	
	int positiveNumber = 0;//正数
	int negativeNumber = 0;//负数
	while(true){
	
	int number = scan.nextInt();
	if(number > 0){
	positiveNumber++;
	}
	else if(number < 0){
	negativeNumber++;
	}
	else{
	break;	
	}	
}
	
System.out.println("输入的正数的个数为:"+positiveNumber);
System.out.println("输入的负数的个数为:"+negativeNumber);	
	
}

九九乘法表

class NineNineTable{
	public static void main(String[] args){
	System.out.println("Hello World");
         for(int i =1;i<=9;i++){
		for(int j=1;j<=i;j++){
			System.out.print(i + "*" +j+"="+(i*j)+" ");
			}System.out.println();
		}
	}	
}

100以内的素数

class PrimeNumberTest{
	public static void main(String[] args){
	long start = System.currentTimeMillis;
	for(int i = 2;i<=100;i++){
boolean isflag = true;
		for(int j = 2;j<i;j++){   //j <=Math.sqrt(i);
			if(i%j==0){
				isflag = false;
				break;  
				}
			}
		if(isflag==true){
			System.out.println(i);
			}
   		}
   		long end = System.currentTimeMillis;
   		System.out.println("所花费的时间为:"+(end-start));
	}
}

(二).数组

public class ArrayTest {
	public static void main(String[] args) {
		int num;//声明
		num = 10;//初始化
		int id = 1001;//声明+初始化
		
		int[] ids;
		//静态初始化
		ids = new int[] {1001,1002,1003,1004};
		//动态初始化
		String[] names = new String[5];
		//用脚标方式调用
		names[0] = "张";
		names[1] = "李";
		names[2] = "赵";
		names[3] = "钱";
		names[4] = "孙";
		//获取数组的长度;
		System.out.println(names.length);
		System.out.println(ids.length);
		//遍历数组
		for(int i = 0;i <names.length ;i++) {
			System.out.println(names[i]);
		}
		//数组元素的默认初始化值是int,short0,
		//float是0.0,char是0;
		//boolean是false
		//String是null
		
	}
	 
}
import java.util.Scanner;

public class ArrayTest1 {
	public static void main(String [] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("输入学生人数");
		int number = scanner.nextInt();
		
		int [] scores = new int[number];
		System.out.println("输入学生成绩");
		for(int i = 0;i<scores.length;i++) {
			scores[i] = scanner.nextInt();
		}
		//获取数组中元素的最大值
		int max =0;
		for(int i= 0;i<scores.length ;i++) {
			if(max<scores[i]) {
				max = scores[i];
			}
		}
		System.out.println(max);
	}

}
 
public class ArrayTest2 {
	public static void main(String[] args) {
		int[] arr = new int [] {1,2,3};
		//静态初始化
		int[][] arr1 = new int[][] {{1,2,3},{4,5},{6,7,8}};
		//动态初始化 
		String[][] arr2 = new String[3][2];
		
		System.out.println(arr1.length);
		System.out.println(arr1[1].length);
		
	}
}

1.数组应用

public class ArrayTest3 {
	public static void main(String[] args) {
		 int[] arr = new int [] { 8,2,1,0,3};
		 int[] index = new int[] {2,0,3,2,4,0,1,3,2,3,3};
		 String tel  = "";
		 for(int i =0;i<index.length;i++) {
			 tel+=arr[index[i]];
			 }
		 System.out.println("联系方式:" + tel);// 
		 
	}

}
public class ArrayTest4 {
	public static void main(String[] args) {
		int[][] arr1 = new int[][] {{1,2,3},{4,5},{6,7,8}};
		//调用二位数组
		System.out.println(arr1[0][1]);
		//如何获取数组的长度
		System.out.println(arr1.length);//3
		System.out.println(arr1[0].length);//3
		System.out.println(arr1[1].length);//2
		//如何遍历二维数组
		for(int i=0;i <arr1.length;i++) {            
			for(int j = 0;j<arr1[i].length;j++) {
				System.out.print(arr1[i][j]+" ");
			}
			System.out.println();
		}
	}

}
/*1 2 3 
4 5 
6 7 8 
*/

2.计算数组总和

package com.atguigu.java;

public class Arry {

	public static void main(String args[]) {
		int[][] arr = new int[][] {{3,5,8},{12,9},{7,0,6,4}};
		int sum = 0;
		for(int i = 0;i<arr.length;i++) {
			for(int j = 0;j<arr[i].length;j++) {
				sum+=arr[i][j];
			}
		}System.out.println("总和为:"+sum);
	}
}

3.杨辉三角

public class YangHui {
	public static void main(String[] args) {
		int[][]yanghui = new int[10][];
		//给数组元素赋值
		for(int i = 0;i<yanghui.length;i++ ) {
			yanghui[i] = new int[i+1];
			yanghui[i][0]=1;
			yanghui[i][i]=1;
			if(i>1) {
				for(int j=1;j<yanghui[i].length-1;j++) {
					yanghui[i][j] = yanghui[i-1][j-1]+yanghui[i-1][j];
				}
			}
		}
		//遍历
		for(int i = 0;i<yanghui.length;i++) {
			for(int j= 0;j<yanghui[i].length;j++) {
				System.out.print(yanghui[i][j]+" ");
			}
			System.out.println();
		}
	}

}

4.随机数里面取最大的

public class algorithm {
	public static void main(String[] args) {
		//Math.random()*(99-10+1)+10
		int[] arr  =new int[10];
		for(int i =0;i<arr.length;i++) {
			arr[i]=(int)(Math.random()*(99-10+1));
		}
		int max =0;
		for(int i =0;i<arr.length;i++) {
			if(max<arr[i]) {
				max = arr[i];
			}
		}
		System.out.println("最大值为:"+max);
	}
		
}

5.数组反转

public class algorithm1 {
	public static void main(String[] args) {
		 String[]arr = new String[] {"JJ","DD","MM","BB","GG","AA"};
		 
		 //数组的反转
		 for(int i=0;i<arr.length/2;i++) {
			 String temp =arr[i];
			 arr[i]=arr[arr.length-i-1];
			 arr[arr.length-i-1]=temp;
		 }
		 for(int i = 0;i<arr.length;i++) {
			 System.out.print(arr[i]+"\t");
		 }
	}

}

6.线性查找

	 boolean flag = true;
		 String dest ="BB";
		 for(int i=0;i<arr.length;i++) {
			 if(dest.equals(arr[i])) {
				 flag = false;
				 System.out.println("找到了,位置"+i);
				 break;
			 }
		 }
		 if(flag) {
			 System.out.println("没找到");
			 
		 }

7.二分查找

public static void main(String[] args) {
	int [] arr2 =  new int[]{-98,-34,2,34,54,66,79,105,210,333};
	int dest = 34;
	int head = 0;
	int end = arr2.length - 1;
	while(head<=end) {
		int middle = (head + end)/2;
		if(dest ==arr2[middle]) {
			System.out.println("找到了指定元素,位置为:"+middle);
			break;
		}
		else if(arr2[middle]>dest) {
			end = middle-1;
		}
		else {
			head = middle+1;
		}
	}

}

8.冒泡排序

public static void main(String[]args) {
		//冒泡排序
		int []arr = new int[] {43,32,76,-98,0,64,33,-21,32,99};
		for(int i = 0;i<arr.length-1;i++) {
			for(int j=0;j<arr.length-1-i;j++) {
				if(arr[j]>arr[j +1]) {
					int temp =arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		for(int i=0;i<arr.length-1;i++) {
			System.out.print(arr[i]+" ");
		}
	}

9.Arrys用法

public class ArrysTestjava {
	public static void main(String[]args) {
		//判断两个类型的数学组是否相等
		 int []arr1 = new int[] {1,2,3,4};
		 int []arr2 = new int[] {1,3,2,4};
		 boolean isEquals = Arrays.equals(arr1, arr2);
		  System.out.println(isEquals);
		  
		  //输出数组信息
		  System.out.println(Arrays.toString(arr1));
		   
		  //将指定值填充到数组之中
		  Arrays.fill(arr2,5);
		  System.out.println(Arrays.toString(arr2));
		  //对数组进行排序
		  Arrays.sort(arr1);
		  System.out.println(Arrays.toString(arr1));
		  //二分查找
		  int[]arr3 = new int[] {-22,-34,-12,4,57,45,67,56,99};
		  int index = Arrays.binarySearch(arr3, 57);
		  System.out.println(index);
	}

}
 

(三)面向对象(上)

类和对象的使用(面向对象)
1.创建类,设计类的对象
2.创建类的对象
3.通过“对象.属性”或“对象.方法"调用对象的结构


public class PersonTest {
	
	
		public static void main(String[] args) {
			//创建Person类的对象
			Person p1 = new Person();
			//Scanner scanner = newSanner(System.in);
			//调用对象的结构,属性,方法
			//调用属性
			p1.name = "Tom";
			p1.isMale = true;
			System.out.println(p1.name);
			//调用方法
			p1.eat();
			p1.talk("Chinese");
			p1.sleep();
		}
	}
	class Person{
		//属性(成员变量)
		String name;
		int age  = 1;
		boolean isMale;
		//方法 = 成员方法 = 函数 = method
		public void eat() {
			System.out.println("人可以吃饭");
		}
		public void sleep() {
			System.out.println("人可以睡觉");
		}
		public void talk(String language) {
			System.out.println("人可以说话,使用的是:"+language);
			
		}
	}


```java
class Customer{ 
	String name;
	int age;
	boolean isMale;
	public void eat() {
		System.out.println("客户吃饭");
	}
	public void sleep(int hour) {
		System.out.println("休息了"+hour+"个小时");
		
	}
	public String getName() {
		return name;
		
	}
	public String getNation(String nation) {
		String info = "我的国籍是:"+nation;
		return info;
	}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ProductCategory {
    private String categoryName;

    public ProductCategory(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryName() {
        return categoryName;
    }
}

class Product {
    private int productId;
    private String productName;
    private double price;

    public Product(int productId, String productName, double price) {
        this.productId = productId;
        this.productName = productName;
        this.price = price;
    }

    public int getProductId() {
        return productId;
    }

    public String getProductName() {
        return productName;
    }

    public double getPrice() {
        return price;
    }
}

public class EcommercePlatform {
    private static List<ProductCategory> categories = new ArrayList<>();
    private static List<Product> products = new ArrayList<>();
    private static int productIdCounter = 1;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("电商购物平台");
            System.out.println("1. 添加商品类目");
            System.out.println("2. 添加商品");
            System.out.println("3. 修改商品信息");
            System.out.println("4. 查询商品信息");
            System.out.println("5. 退出");
            System.out.print("请选择操作:");

            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline character

            switch (choice) {
                case 1:
                    System.out.print("请输入商品类目名称:");
                    String categoryName = scanner.nextLine();
                    ProductCategory category = new ProductCategory(categoryName);
                    categories.add(category);
                    System.out.println("商品类目添加成功!");
                    break;
                case 2:
                    System.out.print("请输入商品名称:");
                    String productName = scanner.nextLine();
                    System.out.print("请输入商品价格:");
                    double price = scanner.nextDouble();
                    scanner.nextLine(); // Consume newline character

                    Product product = new Product(productIdCounter++, productName, price);
                    products.add(product);
                    System.out.println("商品添加成功!");
                    break;
                case 3:
                    System.out.print("请输入要修改的商品ID:");
                    int productIdToUpdate = scanner.nextInt();
                    scanner.nextLine(); // Consume newline character

                    Product productToUpdate = findProductById(productIdToUpdate);
                    if (productToUpdate != null) {
                        System.out.print("请输入新的商品名称:");
                        productName = scanner.nextLine();
                        System.out.print("请输入新的商品价格:");
                        price = scanner.nextDouble();
                        scanner.nextLine(); // Consume newline character

                        productToUpdate = new Product(productToUpdate.getProductId(), productName, price);
                        products.set(products.indexOf(findProductById(productIdToUpdate.getProductId())), productToUpdate);
                        System.out.println("商品信息修改成功!");
                    } else {
                        System.out.println("商品不存在!");
                    }
                    break;
                case 4:
                    System.out.print("请输入要查询的商品ID:");
                    int productIdToQuery = scanner.nextInt();
                    scanner.nextLine(); // Consume newline character

                    Product productToQuery = findProductById(productIdToQuery);
                    if (productToQuery != null) {
                        System.out.println("商品ID: " + productToQuery.getProductId());
                        System.out.println("商品名称: " + productToQuery.getProductName());
                        System.out.println("商品价格: " + productToQuery.getPrice());
                    } else {
                        System.out.println("商品不存在!");
                    }
                    break;
                case 5:
                    System.out.println("感谢使用电商购物平台!");
                    scanner.close();
                    System.exit(0);
                default:
                    System.out.println("无效选项,请重新选择!");
            }
        }
    }

    private static Product findProductById(int productId) {
        for (Product product : products) {
            if (product.getProductId() == productId) {
                return product;
            }
        }
        return null;
    }
}

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ProductCategory {
    private String categoryName;

    public ProductCategory(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryName() {
        return categoryName;
    }
}

class Product {
    private int productId;
    private String productName;
    private double price;

    public Product(int productId, String productName, double price) {
        this.productId = productId;
        this.productName = productName;
        this.price = price;
    }

    public int getProductId() {
        return productId;
    }

    public String getProductName() {
        return productName;
    }

    public double getPrice() {
        return price;
    }
}

public class EcommercePlatform {
    private static List<ProductCategory> categories = new ArrayList<>();
    private static List<Product> products = new ArrayList<>();
    private static int productIdCounter = 1;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("电商购物平台");
            System.out.println("1. 添加商品类目");
            System.out.println("2. 添加商品");
            System.out.println("3. 修改商品信息");
            System.out.println("4. 查询商品信息");
            System.out.println("5. 退出");
            System.out.print("请选择操作:");

            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline character

            switch (choice) {
                case 1:
                    System.out.print("请输入商品类目名称:");
                    String categoryName = scanner.nextLine();
                    ProductCategory category = new ProductCategory(categoryName);
                    categories.add(category);
                    System.out.println("商品类目添加成功!");
                    break;
                case 2:
                    System.out.print("请输入商品名称:");
                    String productName = scanner.nextLine();
                    System.out.print("请输入商品价格:");
                    double price = scanner.nextDouble();
                    scanner.nextLine(); // Consume newline character

                    Product product = new Product(productIdCounter++, productName, price);
                    products.add(product);
                    System.out.println("商品添加成功!");
                    break;
                case 3:
                    System.out.print("请输入要修改的商品ID:");
                    int productIdToUpdate = scanner.nextInt();
                    scanner.nextLine(); // Consume newline character

                    Product productToUpdate = findProductById(productIdToUpdate);
                    if (productToUpdate != null) {
                        System.out.print("请输入新的商品名称:");
                        productName = scanner.nextLine();
                        System.out.print("请输入新的商品价格:");
                        price = scanner.nextDouble();
                        scanner.nextLine(); // Consume newline character

                        productToUpdate = new Product(productToUpdate.getProductId(), productName, price);
                        products.set(products.indexOf(findProductById(productIdToUpdate.getProductId())), productToUpdate);
                        System.out.println("商品信息修改成功!");
                    } else {
                        System.out.println("商品不存在!");
                    }
                    break;
                case 4:
                    System.out.print("请输入要查询的商品ID:");
                    int productIdToQuery = scanner.nextInt();
                    scanner.nextLine(); // Consume newline character

                    Product productToQuery = findProductById(productIdToQuery);
                    if (productToQuery != null) {
                        System.out.println("商品ID: " + productToQuery.getProductId());
                        System.out.println("商品名称: " + productToQuery.getProductName());
                        System.out.println("商品价格: " + productToQuery.getPrice());
                    } else {
                        System.out.println("商品不存在!");
                    }
                    break;
                case 5:
                    System.out.println("感谢使用电商购物平台!");
                    scanner.close();
                    System.exit(0);
                default:
                    System.out.println("无效选项,请重新选择!");
            }
        }
    }

    private static Product findProductById(int productId) {
        for (Product product : products) {
            if (product.getProductId() == productId) {
                return product;
            }
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值