Recommendation::Main.java

本文介绍了如何使用MySQL数据库进行用户信息插入,并实现基于用户兴趣的推荐系统,通过交互式输入获取用户偏好并生成个性化推荐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package pA;

import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
import java.math.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
	public static Recommend[] arr;
	public static Pair[] arrp;
	public static Scanner input;
	public static Recommend A;
	public static int n;
	public static int num;
	public static int information;
	
	//JDBC的协议、主机名(此处是本地机)、端口号、需要连接的数据库等信息
    public static String url = "jdbc:mysql://localhost:3306/recommend";
    public static String user = "root";                   //登录用户名
    public static String password = "123456";             //登录密码
    
    public static Connection con;
    public static Statement stmt;
	
	public static void main(String[] args) {
		setup();
		loop();
	}
	
	public static void setup() {
		
        try {
        	Class.forName("com.mysql.jdbc.Driver"); //指定MySQL驱动。
            con = DriverManager.getConnection(url, user, password);  //连接MySQL数据库
            System.out.println("连接数据库服务器成功。");
            stmt = con.createStatement();
        } catch (ClassNotFoundException e) {    //捕获没有找到驱动的异常,是forName()方法抛出的。
            System.out.println("没有找到MySQL驱动。");
        } catch (SQLException e) {              //捕获连接失败的异常,是Connection对象抛出的。
            System.out.println("连接数据库服务器失败。");
        }
        
        
        
        
        String chars = "abcdefghijklmnopqrstuvwxyz";	//!!!here
        //String sql1 = "INSERT INTO user VALUES(0,1,2,3,4,5,6,7,'Zhangsan')";
        String sql1 = "INSERT INTO user VALUES("+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		"'"+
        		"Zhangsan"+	//单字母用户
        		"')";
        try {
        	int cnt1 = stmt.executeUpdate(sql1);//执行UPDATE语句,返回更新的记录数。  
        	if (cnt1 != 0) {  
        		System.out.println("INSERT语句执行成功。");
        	}
        } catch (SQLException e) {              //捕获连接失败的异常,是Connection对象抛出的。
            System.out.println("连接数据库服务器失败。");
        }
        
        
        //again
        Random random = new Random();
        
        //System.out.println(chars.charAt((int)(Math.random() * 26)));
        for (int i = 0; i < 10; i++) {
        	String tmp = "INSERT INTO user VALUES("+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		"'"+
        		chars.charAt((int)(Math.random() * 26))+	//用户
        		chars.charAt((int)(Math.random() * 26))+
        		"')";
        	try {
            	int cnt1 = stmt.executeUpdate(tmp);//执行UPDATE语句,返回更新的记录数。  
            	if (cnt1 != 0) {  
            		System.out.println("INSERT语句执行成功。");
            	}
            } catch (SQLException e) {              //捕获连接失败的异常,是Connection对象抛出的。
                System.out.println("连接数据库服务器失败。");
            }	
        }
        
        //again1
        for (int i = 0; i < 10; i++) {
        	String tmp = "INSERT INTO feature VALUES("+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		Math.random()+","+
        		"'"+
        		chars.charAt((int)(Math.random() * 26))+	//商品名
        		chars.charAt((int)(Math.random() * 26))+
        		"')";
        	try {
            	int cnt1 = stmt.executeUpdate(tmp);//执行UPDATE语句,返回更新的记录数。  
            	if (cnt1 != 0) {  
            		System.out.println("INSERT语句执行成功。");
            	}
            } catch (SQLException e) {              //捕获连接失败的异常,是Connection对象抛出的。
                System.out.println("连接数据库服务器失败。");
            }
        }
        
        
        
        
		System.out.println("Please input the number of features of one vector.");
		input = new Scanner(System.in);
		n = input.nextInt();
		
		System.out.println("Please input the considering vector.");
		A = new Recommend(n);
				
		System.out.println("Please input the number of comparing vectors.");
		num = input.nextInt();
		System.out.println("Please input these vectors.");
		arr = new Recommend[num];
		for (int i = 0; i < num; i++) {
			arr[i] = new Recommend(n);
		}
		//Recommend B = new Recommend(n);
		//double s = A.getSimiliar(B);
		//System.out.print("The similiar factor is ");
		//System.out.println(s);
		
		arrp = new Pair[num];
	}
	
	public static void loop() {
		while (true) {
			catchInfo();
			//dealWithInfo();
		}
	}
	
	public static void catchInfo() {
		System.out.println("Please input the kind of information.");
		System.out.println("1 for update; 2 for output to screen.");
		information = input.nextInt();
		switch (information) {
		case 1:
			update();
			break;
		case 2:
			outputToScreen();
		}
	}
	
	//public static void dealWithInfo() {
		
	//}
	
	public static void outputToScreen() {
		System.out.println("Input recommend mode:");
		System.out.println("0 for all; 1 for part; 2 for this user's preference.");
		int mode = input.nextInt();
		if (mode == 0) {
			for (int i = 0; i < num; i++) {
				arrp[i] = new Pair(i, A.getSimiliar(arr[i]));
			}
		} else if (mode == 1) {
			System.out.println("Input the part of recommend.");
			int index = input.nextInt();
			for (int i = 0; i < num; i++) {
				arrp[i] = new Pair(i, A.getSimiliarPartOf(arr[i], index));
			}
		} else if (mode == 2) {
			for (int i = 0; i < num; i++) {
				arrp[i] = new Pair(i, A.getThisUsersPrefer(arr[i]));
			}
		}
		
		Arrays.sort(arrp, new PairCmp());
		//System.out.println("The pre " + num + " number of goods and the recommend rates are:");
		System.out.println("The pre " + num + " number of goods are:");
		for (int i = 0; i < num; i++) { //输出前num个物品,推荐度依次降低
			//System.out.println((int)arrp[i].first + " " + arrp[i].second);
			System.out.println((int)arrp[i].first);
		}
	}
	
	public static void update() {
		System.out.println("Please input the way which the customer view or buy.");
		System.out.println("1 for view; 2 for buy.");
		int w = input.nextInt();
		if (w == 1) {
			A.rate[0] += 1;
			A.maintainRate();
			for (int i = 0; i < n; i++) {
				A.feature[i] = A.rate[i];
			}
		} else if (w == 2) {
			A.rate[0] += 3;
			A.maintainRate();
			for (int i = 0; i < n; i++) {
				A.feature[i] = A.rate[i];
			}
		} else {
			System.out.println("Input wrong.");
		}
	}
}


<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.onlinebookstore"> <!-- 记得添加下面的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <application android:allowBackup="true" android:icon="@drawable/s2" android:label="在线书店" android:requestLegacyExternalStorage="true" android:supportsRtl="true" android:theme="@style/Theme.FlowerShop"> <activity android:name=".activity.LoginActivity"/> <activity android:name=".activity.WelcomeActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.ManageActivity" android:exported="false" /> <activity android:name=".activity.StuffEditActivity" android:exported="false" /> <activity android:name=".activity.LoginActivity" android:exported="false" /> <activity android:name=".activity.RegisterActivity" android:exported="false" /> <activity android:name=".activity.MainActivity" android:exported="false" /> <activity android:name=".activity.DetailActivity" android:exported="false" /> <activity android:name=".activity.AboutActivity" android:exported="false" /> <activity android:name=".activity.InfoActivity" android:exported="false" /> <activity android:name=".activity.RecordActivity" android:exported="false" /> </application> </manifest>。plugins { id 'com.android.application' } android { namespace 'com.example.flowershop' compileSdk 34 defaultConfig { applicationId "com.example.onlinebookstore" minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'com.github.getActivity:XXPermissions:20.0' implementation ('com.github.bumptech.glide:glide:4.16.0'){ exclude group : 'androidx.annotation' } annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0' }。下面是报错信息Executing tasks: [testDebugUnitTest] in project E:\7.flower-shop\flower-shop\app Starting Gradle Daemon... Connected to the target VM, address: '127.0.0.1:49946', transport: 'socket' Gradle Daemon started in 2 s 237 ms > Task :app:preBuild UP-TO-DATE > Task :app:preDebugBuild UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:checkDebugAarMetadata UP-TO-DATE > Task :app:generateDebugResValues UP-TO-DATE > Task :app:mapDebugSourceSetPaths > Task :app:generateDebugResources UP-TO-DATE > Task :app:mergeDebugResources UP-TO-DATE > Task :app:packageDebugResources UP-TO-DATE > Task :app:parseDebugLocalResources UP-TO-DATE > Task :app:createDebugCompatibleScreenManifests UP-TO-DATE > Task :app:extractDeepLinksDebug UP-TO-DATE > Task :app:processDebugMainManifest FAILED Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. > Task :app:preDebugUnitTestBuild UP-TO-DATE > Task :app:javaPreCompileDebugUnitTest UP-TO-DATE > Task :app:processDebugUnitTestJavaRes NO-SOURCE FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugMainManifest'. > Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 10s 12 actionable tasks: 2 executed, 10 up-to-date 21:07:28: Execution finished 'testDebugUnitTest'. Disconnected from the target VM, address: '127.0.0.1:49946', transport: 'socket'。该修改那些地方让它成为新的项目onlinebooksotre
最新发布
06-03
plugins { id 'com.android.application' } android { namespace 'com.example.flowershop' compileSdk 34 defaultConfig { applicationId "com.example.onlinebookstore" minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'com.github.getActivity:XXPermissions:20.0' implementation ('com.github.bumptech.glide:glide:4.16.0'){ exclude group : 'androidx.annotation' } annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0' }下面是报错信息Executing tasks: [testDebugUnitTest] in project E:\7.flower-shop\flower-shop\app Starting Gradle Daemon... Connected to the target VM, address: '127.0.0.1:61278', transport: 'socket' Gradle Daemon started in 3 s 461 ms > Task :app:preBuild UP-TO-DATE > Task :app:preDebugBuild UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:checkDebugAarMetadata UP-TO-DATE > Task :app:generateDebugResValues UP-TO-DATE > Task :app:mapDebugSourceSetPaths UP-TO-DATE > Task :app:generateDebugResources UP-TO-DATE > Task :app:mergeDebugResources UP-TO-DATE > Task :app:packageDebugResources UP-TO-DATE > Task :app:parseDebugLocalResources UP-TO-DATE > Task :app:createDebugCompatibleScreenManifests > Task :app:extractDeepLinksDebug UP-TO-DATE > Task :app:processDebugMainManifest FAILED Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. > Task :app:preDebugUnitTestBuild UP-TO-DATE > Task :app:javaPreCompileDebugUnitTest UP-TO-DATE > Task :app:processDebugUnitTestJavaRes NO-SOURCE FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugMainManifest'. > Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. >
06-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值