发表于: 2017-07-31 16:32:59
2 963
今日完成:
抽彩游戏代码:
package com.jinhege;
import java.util.Arrays;
import java.util.Scanner;
public class LotteryDrawing {
public static void main(String[] args) {
// write your code here
Scanner in = new Scanner(System.in);
System.out.println("How many numbers do you need to draw?");//draw 抽彩/抽签/抽奖
int k = in.nextInt();
System.out.println("What is the highest number you can draw?");
int n = in.nextInt();
//fill an array with number 1 2 3 ...n
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
numbers[i] = i + 1;
//draw k numbers and put them into a second array
int[] result = new int[k];
for (int i = 0; i < result.length; i++) {
//make a random index between 0 and n-1
int r = (int) (Math.random() * n);
//pick the element at the random location
result[i] = numbers[r];
/*确保不会再次抽取到那个数值,因为所有抽彩的数值必须不同,
因此,这里用数组中的最后一个数值改写numbers[r],并将n减1
*/
//move the last element into the random location
numbers[r] = numbers[n - 1];
n--;
}
//print the sorted array
Arrays.sort(result);
System.out.println("Bet the following combination.It' ll make you rich!");
for (int r : result)
System.out.print(r+" ");
}
}
Console:
How many numbers do you need to draw?
6
What is the highest number you can draw?
99
Bet the following combination.It' ll make you rich!
7 30 69 71 88 94
Process finished with exit code 0
正常运行
明日计划:学习junit
遇到的问题:
表结构:
项目目录:
JdbcCustomerDao
package com.jinhege.customer.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.jinhege.customer.D.CustomerDAO;
import com.jinhege.customer.model.Customer;
public class JdbcCustomerDao implements CustomerDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER" + "(cust_id,name,age)VALUES(?,?,?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
// ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
public Customer findByCustomerId(int custId) {
String sql = "SELECT *FROM CUSTOMER WHERE CUST_ID = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer = new Customer(
rs.getInt("CUST_ID"),
rs.getString("NAME"),
rs.getInt("Age")
);
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
}
package com.jinhege.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jinhege.customer.D.CustomerDAO;
import com.jinhege.customer.model.Customer;
public class App {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context =
new ClassPathXmlApplicationContext("application.xml");
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
Customer customer = new Customer(1, "Thrudy",22);
customerDAO.insert(customer);
Customer customer1 = customerDAO.findByCustomerId(1);
System.out.println(customer1);
}
}
Spring-Customer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerDAO"
class="com.jinhege.customer.dao.impl.JdbcCustomerDao">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Spring-Datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="jinhege" />
</bean>
</beans>
application,xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<import resource="database/Spring-Datasource.xml" />
<import resource="customer/Spring-Customer.xml" />
</beans>
注释下面这句后:
// ps.executeUpdate();
Console:
输出好怪异。。。
package com.jinhege.customer.model;
import java.sql.Timestamp;
//添加客户类型用来存储用户的数据
public class Customer {
int custId;
String name;
int age;
public Customer(int custId, String name, int age) {
}
public int getCustId() {
return custId;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
不注释:
ps.executeUpdate();
七月 31, 2017 2:47:38 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2e0fa5d3: startup date [Mon Jul 31 14:47:38 CST 2017]; root of context hierarchy
七月 31, 2017 2:47:38 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [application.xml]
七月 31, 2017 2:47:39 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [database/Spring-Datasource.xml]
七月 31, 2017 2:47:39 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [customer/Spring-Customer.xml]
七月 31, 2017 2:47:39 下午 org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
信息: Loaded JDBC driver: com.mysql.jdbc.Driver
Exception in thread "main" java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'NAME' cannot be null
at com.jinhege.customer.dao.impl.JdbcCustomerDao.insert(JdbcCustomerDao.java:31)
at com.jinhege.common.App.main(App.java:16)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'NAME' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at com.jinhege.customer.dao.impl.JdbcCustomerDao.insert(JdbcCustomerDao.java:28)
... 1 more
Process finished with exit code 1
'NAME' cannot be null
思考过可能程序中插入数据失败,在dos里插入了数据:
但是运行结果还是一样。。。
嗯,这个问题又卡了三天,一直解决不了。。。嗯,学junit,来定位问题,这样看错误调又调不对太浪费时间了。
收获:
数组排序:
对数值型数组进行排序,可以使用Arrays类中的sort方法:
Math.random()方法返回一个0到1之间(包含0不包含1)的随机浮点数。
int r = (int)(Math.random()*n); //[0,n-1] 双闭
方法executeUpdate()
用于执行INSERT,UPDATE或DELETE语句以及SQL DDL(数据定义语言)语句 如create table 和 drop table
insert,update或delete语句的效果是修改表中0行或多行中的一列或多列
executeUpdate的返回值是一个整数,指示受影响的行数(即更新计数)
对于create table 和 drop table等不操作行的语句,excuteUpdate的返回值总为0
代码块”有两种流行(也是行业都遵守的习惯)的写法,
即Allmans风格和Kernighan风格
Allmans风格:
Allmans风格也称“独行”风格,即左、右大括号各自独占一行
当代码量较少时适合使用“独行”风格,此时代码布局清晰、可读性强。
Kernighan风格:
Kernighan风格也称“行尾”风格,即左大括号在上一行的行尾,而右大括号独占一行
当代码量较多时不适合使用“独行”风格,因为该风格将导致代码的左半部分出现大量的左、右大括号,导致代码清晰度下降,这时应当使用“行尾”风格。
评论