List操作错误Exception in thread "main" java.lang.IllegalStateException
Iterator<Teacher> iter = teacherList.iterator();
while(iter.hasNext()){
    Teacher teacher =iter.next();
    //①查找老师的最大上限值,如果该老师已经达到上限了,则将该老师从List中拿出,不予安排
    if(teacher.getMaxnum()<=teacher.getRealnum()){
    iter.remove();
    teacherList.remove(teacher);
    }
    //②找到该考试的时间点,如果该考试桶中存在与该老师的ID则将该老师摘除,不予考虑.
    if(examBarrelDao.isRelated(exam,teacher)){
    iter.remove();
    teacherList.remove(teacher);
    }
    }
    //③按照监考上限减去监考下限差额最大的顺序排列,取该老师序列的第一个为最优老师。
    for(int i=0;i<teacherList.size()-1;i++){
        for (int j=i+1;j<teacherList.size();j++){
        Teacher teacher = new Teacher();
        if(teacherList.get(i).getMaxnum()-teacherList.get(i).getRealnum()
                                <teacherList.get(j).getMaxnum()-teacherList.get(j).getRealnum()){
                teacher =teacherList.get(i);
                teacherList.set(i, teacherList.get(j));
                teacherList.set(j, teacher);
                }
            }

我将得到的List判断以后,remove了其中的不符合条件的teacher,然后将List中剩余的teacher重新按照大小进行了一次排序,但是有时报 Exception in thread "main" java.lang.IllegalStateException
at java.util.AbstractList$Itr.remove(Unknown Source)
at com.sdjzglxy.jwMis.help.ConditionalJudge.listTeacher(ConditionalJudge.java:229)
at com.sdjzglxy.jwMis.help.ConditionalJudge.teacherChoiceForSecond(ConditionalJudge.java:162)
at com.sdjzglxy.jwMis.action.ArrayExam.arraySecondTeacher(ArrayExam.java:132)
at com.sdjzglxy.jwMis.action.ArrayExam.main(ArrayExam.java:159)
有时对有时错,我想问一下,该如何解决这个问题……

1个回答

iter.remove();
teacherList.remove(teacher);

你删除两次,只用iter.remove(); 就行了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
大家帮我看看这个异常信息
Exception in thread "Main Thread" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cn.com.obj.model.po.std.SysRole.rights, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at test.PermissionTest.main(PermissionTest.java:17) 测试: public class PermissionTest { public static void main(String[] args) { ApplicationContext act=new FileSystemXmlApplicationContext("classpath:cn/com/myweb/spring/applicationContext.xml"); IUserInfoBiz userInfoBiz=(IUserInfoBiz) act.getBean("userInfoBiz"); List<UserInfo> users=userInfoBiz.userInfoList(); System.err.println(users.size()); System.err.println(users.get(0).getRole().getRights().size()); } } hb.xml文件: userinfo: <hibernate-mapping package="cn.com.obj.model.po.std"> <class name="UserInfo" table="UserInfo"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="userName" column="userName" type="java.lang.String" length="40" not-null="false" /> <property name="password" column="password" type="java.lang.String" length="40" not-null="false" /> <property name="age" column="age" type="java.lang.Integer" /> <property name="sex" column="sex" type="java.lang.String" /> <property name="job" column="job" type="java.lang.String" /> <many-to-one name="role" class="SysRole" fetch="select" lazy="false"> <column name="roleID" not-null="true"></column> </many-to-one> </class> </hibernate-mapping> SysRole: <hibernate-mapping package="cn.com.obj.model.po.std"> <class name="SysRole" table="SysRole"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="name" column="name" type="java.lang.String" /> <property name="enable" column="enable" type="java.lang.Boolean" /> <property name="descn" column="descn" type="java.lang.String" /> <property name="rank" column="rank" type="java.lang.Integer" /> <property name="createTime" column="createTime" type="java.util.Date" /> <!-- --> <bag name="rights" inverse="true" table="sys_role_right"> <key> <column name="roleID" not-null="true"/> </key> <many-to-many entity-name="cn.com.obj.model.po.std.SysRight"> <column name="rightID" not-null="true"></column> </many-to-many> </bag> <bag name="users" inverse="true"> <key> <column name="roleID" not-null="true"></column> </key> <one-to-many class="UserInfo"/> </bag> </class> </hibernate-mapping> SysRight: <hibernate-mapping package="cn.com.obj.model.po.std"> <class name="SysRight" table="SysRight"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="parentId" column="parentId" type="java.lang.Integer" /> <property name="rname" column="rname" type="java.lang.String" /> <property name="tooltip" column="tooltip" type="java.lang.String" /> <property name="commandKey" column="commandKey" type="java.lang.String" /> <property name="jsPath" column="jsPath" type="java.lang.String" /> <property name="res" column="res" type="java.lang.String" /> <bag name="roles" inverse="true" table="sys_role_right"> <key> <column name="rightID" not-null="true"/> </key> <many-to-many entity-name="cn.com.obj.model.po.std.SysRole"> <column name="roleID" not-null="true"></column> </many-to-many> </bag> </class> </hibernate-mapping>
JAVA list集合内以Map格式 强制转换map怎么做?
我从数据库取出数据放到list中想要将list转化为Map ``` System.out.println(list1.get(0)); ``` 打印出来的结果是 :uname:李华 list里面是以Map的格式存在的,怎么把list强制转化为Map,使用以下代码时出错了 ``` Map maps = (Map) list1.get(0); ``` ``` Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map ```
hibernate的java.lang.NoSuchMethodError
[code="java"] public void updDb(Session session){ try{ String hql = "select * from Sample"; Query qr = session.createQuery(hql); List list = qr.list(); for(int i = 0; i < list.size(); i++){ Sample s = (Sample)list.get(i); System.out.println(s.getSampleId()+" : "+s.getName()); } } catch(HibernateException e){ e.printStackTrace(); } [/code] 下面是错误: 2010-11-25 13:35:48,567 ERROR [org.hibernate.hql.PARSER] - line 1:8: unexpected token: * Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V 怎么解决? 自己看出问题了,是查询语句写错了,现在想问个问题是使用hibernate查询,前面不能写'select [字段]...'么
Exception in thread "AWT-EventQueue-0"
``` import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.File; import java.io.IOException; public class PipeFilterTestGui extends JPanel { private JScrollPane btnPane; private JSplitPane splitPane; private JSplitPane rightSplitPane; private JTextArea originalTxt; private JTextArea resultTxt; private JScrollPane originPane; private JScrollPane resultPane; private JLabel filelbl; private JPanel buttonPanel; private JComboBox cmbFileList; static final String PROCESS = "Process"; static final String EXIT = "Exit"; static final String ORIGINALFILES = "OriginalFiles/"; static final Dimension minimumSize = new Dimension(230, 200); public PipeFilterTestGui() { super(new GridLayout(1, 0)); resultTxt = new JTextArea("Encrypted File Text\n\n", 6, 20); originalTxt = new JTextArea("Original File Text: \n\n", 6, 20); buildUpScrollGUI(); } private void buildUpScrollGUI() { // Setup buttonPanel, which contains all buttons and // will be used in btnPane below setUpButtonPanel(); btnPane = new JScrollPane(buttonPanel); btnPane.setMinimumSize(minimumSize); resultPane = new JScrollPane(resultTxt); originPane = new JScrollPane(originalTxt); rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); rightSplitPane.setLeftComponent(originPane); rightSplitPane.setRightComponent(resultPane); rightSplitPane.setDividerLocation(190); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(btnPane); splitPane.setRightComponent(rightSplitPane); splitPane.setDividerLocation(220); splitPane.setPreferredSize(new Dimension(600, 250)); add(splitPane); setSize(new Dimension(600, 400)); setVisible(true); } private void setUpButtonPanel() { cmbFileList = new JComboBox(); String[] cl = extractFileList(); setupFileList(cmbFileList, cl); filelbl = new JLabel("Files:"); // Create buttons JButton srchButton = new JButton(PROCESS); srchButton.setMnemonic(KeyEvent.VK_S); JButton exitButton = new JButton(EXIT); exitButton.setMnemonic(KeyEvent.VK_X); ButtonListener btnListener = new ButtonListener(); // add action Listener srchButton.addActionListener(btnListener); exitButton.addActionListener(btnListener); buttonPanel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); buttonPanel.setLayout(gridbag); GridBagConstraints gbc = new GridBagConstraints(); buttonPanel.add(filelbl); buttonPanel.add(cmbFileList); buttonPanel.add(srchButton); buttonPanel.add(exitButton); gbc.insets.top = 5; gbc.insets.bottom = 5; gbc.insets.left = 5; gbc.insets.right = 5; gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 0; gridbag.setConstraints(filelbl, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 0; gridbag.setConstraints(cmbFileList, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 1; gbc.insets.left = 2; gbc.insets.right = 2; gbc.insets.top = 25; gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 3; gridbag.setConstraints(srchButton, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 3; gridbag.setConstraints(exitButton, gbc); } /* ========================================= */ /* Get a selected file name from User GUI */ /* ========================================= */ public String getSelectedFile() { return (String) cmbFileList.getSelectedItem(); } /* ================================================ */ /* Extract file names from a diectory on your */ /* computer */ /* ================================================ */ public String[] extractFileList() { File f = new File(ORIGINALFILES); String[] fileNames = f.list(); return fileNames; } /* ============================================== */ /* Add car list to combox cmbFileList. Both */ /* objects cmbFileList and files are passed */ /* in from parameters. */ /* ============================================== */ public void setupFileList(JComboBox cmbFileList, String[] files) { for (int k = 0; k < files.length; k++) { cmbFileList.addItem(files[k]); } } class ButtonListener implements ActionListener { String carPrice; public void actionPerformed(ActionEvent e) { String searchResult = null; if (e.getActionCommand().equals(EXIT)) { System.exit(1); } if (e.getActionCommand().equals(PROCESS)) { String selectedFile = getSelectedFile(); try { originalTxt.append("File Name: " + selectedFile + "\n\n"); resultTxt.append("From file: " + selectedFile + "\n"); AssemblyOfPipeLines apline = new AssemblyOfPipeLines(); apline.assembly(selectedFile, originalTxt, resultTxt); } catch (IOException ex) { } } } } // End of class ButtonListener private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Pipes and Filters Architecture demo- Legacy File Update"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); PipeFilterTestGui newContentPane = new PipeFilterTestGui(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } static public void main(String argv[]) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at PipeFilterTestGui.setupFileList(PipeFilterTestGui.java:150) at PipeFilterTestGui.setUpButtonPanel(PipeFilterTestGui.java:67) at PipeFilterTestGui.buildUpScrollGUI(PipeFilterTestGui.java:37) at PipeFilterTestGui.<init>(PipeFilterTestGui.java:30) at PipeFilterTestGui.createAndShowGUI(PipeFilterTestGui.java:191) at PipeFilterTestGui.access$2(PipeFilterTestGui.java:185) at PipeFilterTestGui$1.run(PipeFilterTestGui.java:205) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) 还有其他几个类。 需要上传吗?
java数据库,出现java.lang.ClassNotFoundException 问题
package S; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; public class JDBCS { String url = "jdbc:mysql://localhost:3307/ty10"; String name = "root"; String password = "mysql"; Connection conn = null; PreparedStatement pps=null; ResultSet rs = null; JDBCS() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,name,password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void update(String sql,String[] val){ try { pps = conn.prepareStatement(sql); for (int i = 0; val!=null && i < val.length; i++) { pps.setString(i+1, val[i]); } pps.executeUpdate(); }catch (SQLException e) { e.printStackTrace(); } } ArrayList<HashMap<String ,String>> queryToList(String sql ,String[] val){ rs=query(sql,val); ArrayList<HashMap<String ,String>> list = new ArrayList<HashMap<String,String>>(); try { ResultSetMetaData mt = rs.getMetaData();//结果集结构对象(有啥字段,类型,长度。。。) while(rs.next()){ HashMap<String ,String> map = new HashMap<String ,String>(); for (int i = 0; i < mt.getColumnCount(); i++) {//取所有字段 String name = mt.getColumnName( i+1 );//获取列名 map.put(name, rs.getString(name)); } list.add(map); } } catch (SQLException e) { e.printStackTrace(); } return list ; } ResultSet query(String sql ,String[] val){ try { pps = conn.prepareStatement(sql); for (int i = 0; val!=null && i < val.length; i++) { pps.setString(i+1, val[i]); } rs = pps.executeQuery(); return rs ; }catch (SQLException e) { e.printStackTrace(); } return null; } void close(){ try { rs.close(); } catch (SQLException e2) { e2.printStackTrace(); } try { pps.close(); } catch (SQLException e1) { e1.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } 运行后错误提示 java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at S.JDBCS.<init>(JDBCS.java:22) at S.student2.main(student2.java:9) Exception in thread "main" java.lang.NullPointerException at S.JDBCS.query(JDBCS.java:81) at S.student2.main(student2.java:10)
将json对象转化为java对象?
TestBean tb = new TestBean(); tb.setName("闫燕飞"); tb.setSex("男"); List<String> list = new ArrayList<String>(); list.add("mother"); list.add("father"); tb.setParentName(list); //将一个实体类对象转化为json对象 JSONObject jo1= JSONObject.fromObject(tb); //将json对象转化为java对象(这里编译通过,执行的时候报异常) TestBean tb1 = (TestBean)JSONSerializer.toJava(jo1); 异常:Exception in thread "main" java.lang.ClassCastException: net.sf.ezmorph.bean.MorphDynaBean cannot be cast to com.second.TestBean
多数据源spring 报java.lang.NullPointerException
在调用test.java的时候就会报 Exception in thread "main" java.lang.NullPointerException at cn.m_solution.mds.mds40.service.MDS40T01Service.getStudent(MDS40T01Service.java:23) at cn.m_solution.mds.mds40.service.test.main(test.java:13) 请大家一定帮忙,已经弄了两天了 [color=red]moduleContext-sys.xml:[/color] <?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-2.5.xsd"> <!-- +++++++++++++++++++++++++++++++++++++++++ --> <!-- 系统关联设定(必须) --> <!-- +++++++++++++++++++++++++++++++++++++++++ --> <bean id="ApplicationInfo" class="net.uniuvo.webridger.beans.ApplicationInfo"> <!-- 应用系统名称 --> <property name="applicationName" value="mds" /> <!-- 允许直接访问的Action列表 --> <property name="directAccessActions"> <list> <value>mds00.do</value> <value>/mds13.do</value> <value>/mds40.do</value> </list> </property> <!-- 禁止访问的扩展名列表 --> <property name="prohibitedExtensions"> <list> <value>js</value> <value>css</value> <value>jsp</value> <value>html</value> </list> </property> <!-- 禁止访问的扩展名中例外的文件列表 --> <property name="restrictionEscapeFiles"> <list> <value>/pages/index.html</value> <value>/pages/mds40/mds40s00.jsp</value> </list> </property> </bean> <!-- +++++++++++++++++++++++++++++++++++++++++ --> <!-- 数据库关联设定(必须) --> <!--此bean告诉Spring去哪找数据库的配置信息,因为有此Bean才出现下面用${}标记来取变量的语句--> <!-- +++++++++++++++++++++++++++++++++++++++++ --> <!-- 这里定义了ibatis的配置文件所在的位置 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>/WEB-INF/config/jdbc/jdbc.properties</value> </property> </bean> <!-- <bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">--> <bean id="ds0" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName0}" /> <property name="url" value="${jdbc.url0}" /> <property name="username" value="${jdbc.username0}" /> <property name="password" value="${jdbc.password0}" /> </bean> <bean id="ds1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName1}" /> <property name="url" value="${jdbc.url1}" /> <property name="username" value="${jdbc.username1}" /> <property name="password" value="${jdbc.password1}" /> </bean> <bean id="DataSource" class="net.uniuvo.webridger.dao.DynamicDataSource"> <property name= "targetDataSources"> <map key-type="java.lang.String"> <entry key="ds0" value-ref="ds0"/> <entry key="ds1" value-ref="ds1"/> </map> </property> <property name="defaultTargetDataSource" ref="ds0"/> </bean> <!--这里就声明了具体的事务 --> <bean id="attrSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource"> <property name="properties"> <props> <prop key="execute*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="select*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <!-- 定义事务处理拦截器 --> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"> <ref local="transactionManager" /> </property> <property name="transactionAttributeSource"> <ref local="attrSource" /> </property> </bean> <!-- 定义事务经理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref local="DataSource" /> </property> </bean> <!-- 自动代理 (业务处理Bean的Id) --> <bean id="autoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="interceptorNames"> <list> <idref bean="transactionInterceptor" /> </list> </property> <property name="beanNames"> <list> <value>*Service</value> </list> </property> </bean> <!-- iBATIS相关设定 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="/WEB-INF/sqlMapConfig.xml" /> <property name="dataSource"> <ref bean="DataSource" /> </property> <property name="lobHandler"> <ref local="oracleLobHandler" /> </property> </bean> <!-- 定义DAO --> <!-- 检索用DAO --> <bean id="queryDAO" class="net.uniuvo.webridger.dao.QueryDAOiBatisImpl"> <property name="sqlMapClient"> <ref local="sqlMapClient" /> </property> </bean> <!-- 追加 更新 删除用DAO --> <bean id="updateDAO" class="net.uniuvo.webridger.dao.UpdateDAOiBatisImpl"> <property name="sqlMapClient"> <ref local="sqlMapClient" /> </property> </bean> <!--根据sqlMapClien创建一个SqlMapClient模版类--> <bean id="SqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient"> <ref bean="sqlMapClient" /> </property> </bean> <bean id="nativeJdbcExtractor" lazy-init="true" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" /> <bean id="oracleLobHandler" lazy-init="true" class="org.springframework.jdbc.support.lob.OracleLobHandler" > <property name="nativeJdbcExtractor"><ref local="nativeJdbcExtractor"/></property> </bean> <!-- 这里就是Facade了,注意,它有个parent属性,就是这个属性,使它的操作受到了事物管理的限制 <bean id="baseFacade" parent="baseTransactionProxy"> <property name="target"> <bean class="facade.BaseFacadeImpl"> 把DAO做为属性注入到Facade中去 <property name="proDao" ref="proDao" /> <property name="errDao" ref="errDao" /> <property name="userDao" ref="userDao" /> <property name="orderDao" ref="orderDao" /> </bean> </property> </bean> --> </beans> [color=red]sqlmapconfig.xml[/color] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <typeHandler jdbcType="BLOB" javaType="[B" callback="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler"/> <typeHandler jdbcType="CLOB" javaType="java.lang.String" callback="org.springframework.orm.ibatis.support.ClobStringTypeHandler" /> <sqlMap resource="../config/sql/sqlMap-mds.xml" /> <sqlMap resource="../config/sql/sqlMap-mds00.xml" /> <sqlMap resource="../config/sql/sqlMap-mds01.xml" /> <sqlMap resource="../config/sql/sqlMap-mds02.xml" /> <sqlMap resource="../config/sql/sqlMap-mds03.xml" /> <sqlMap resource="../config/sql/sqlMap-mds04.xml" /> <sqlMap resource="../config/sql/sqlMap-mds10.xml" /> <sqlMap resource="../config/sql/sqlMap-mds11.xml" /> <sqlMap resource="../config/sql/sqlMap-mds12.xml" /> <sqlMap resource="../config/sql/sqlMap-mds13.xml" /> <sqlMap resource="../config/sql/sqlMap-mds20.xml" /> <sqlMap resource="../config/sql/sqlMap-mds21.xml" /> <sqlMap resource="../config/sql/sqlMap-mds22.xml" /> <sqlMap resource="../config/sql/sqlMap-mds23.xml" /> <sqlMap resource="../config/sql/sqlMap-mds30.xml" /> <sqlMap resource="../config/sql/sqlMap-mds31.xml" /> <sqlMap resource="../config/sql/sqlMap-mds32.xml" /> <sqlMap resource="../config/sql/sqlMap-mds33.xml" /> <sqlMap resource="../config/sql/sqlMap-mds40.xml" /> </sqlMapConfig> sqlMap-mds40.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd"> <sqlMap > <select id="sql.mds40.001" parameterClass="cn.m_solution.mds.mds40.form.MDS40Form" resultClass="cn.m_solution.mds.mds40.form.MDS40Form"> select syr from vehicle where hpzl = #hpzl# and hphm = #hphm# </select> </sqlMap> MDS40T01Service package cn.m_solution.mds.mds40.service; import org.springframework.orm.ibatis.SqlMapClientTemplate; import cn.m_solution.mds.mds40.form.MDS40Form; public class MDS40T01Service { SqlMapClientTemplate sqlMapClientTemplate; public MDS40Form getStudent(){ MDS40Form form40 = new MDS40Form(); sqlMapClientTemplate.queryForObject("sql.mds40.001",form40); return form40; } /** * @return the sqlMapClientTemplate */ public SqlMapClientTemplate getSqlMapClientTemplate() { return sqlMapClientTemplate; } /** * @param sqlMapClientTemplate the sqlMapClientTemplate to set */ public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) { this.sqlMapClientTemplate = sqlMapClientTemplate; } } test.java package cn.m_solution.mds.mds40.service; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class test extends JdbcDaoSupport{ /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MDS40T01Service s = new MDS40T01Service(); s.getStudent(); } }
java中File的声明使用URI报错
想用网络资源写服务器 [list] [*][code="java"]URI ui = new URI("http://xxx.xxxxxxx.com/xxxxxxxx/文件名.xml"); [*] File f = new File(ui); [*] [*] FileInputStream is = new FileInputStream(f) ; [*] BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(is,"utf-8")); [*] [*] String inputLine = null; [*] while ((inputLine = reader.readLine()) != null) { [*] System.out.println(inputLine); [*] }[/code] [/list] 报错如下 [code="java"]Exception in thread "main" java.lang.IllegalArgumentException: URI scheme is not "file" at java.io.File.<init>(Unknown Source) at something.Test1.main(Test1.java:19)[/code] 这是和解?我直接在网页输入该URI可以访问到
SSH出现Caused by: java.lang.OutOfMemoryError: Java
[list=1] [Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/addUser' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'userDAOProxy' while setting bean property 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOProxy' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOProxy' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space Caused by: java.lang.OutOfMemoryError: Java heap space ] [/list]
Runnable 中抛出java.lang.ArrayIndexOutOfBoundsException: -1
[已解决] SimpleDateFormat.format并发调用会有问题private SimpleDateFormat.StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) 里面用了calendar.setTime(date);这玩意是全局的,后面还会调用它,所以并发时候会出问题。 Random中protected Random.next(int bits);采用AtomicLong的CAS操作并发时候不会出问题。 ------------------------------------------------------------------------------ 每个Task有自己的ArrayList实例,在多线程情况下每个ArrayList实例应该不存在并发写入啊,为没什么还报ArrayIndexOutOfBoundsException: -1 求助大神,网上找了好久没结果。 ``` import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static java.lang.System.out; public class TestArrayList { public static void main(String[] args){ TestArrayList t= new TestArrayList(); t.testInsertRows(); } private static int millisecondOf1Day= 1000*3600*24; private static int millisecondOf5Min= 1000*60*5; private static final SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final ExecutorService pool= Executors.newFixedThreadPool(8); public void testInsertRows(){ Random random= new Random(); int taskId= 0; for(int i=0; i< 8; i++){ taskId++; pool.submit(new Task(taskId, 10000, null)); } out.println("all submited!"); } static class Task implements Runnable{ private Integer id; private List<Bean> list; private int rowCount; private int count=0; private Random random; public Task(Integer id, Integer rowCount, Random random){ this.id= id; this.list= new ArrayList<>(rowCount+1); this.rowCount= rowCount; // this.random= random; this.random= new Random(); } @Override public void run() { out.println("task:"+id+" is running! "+Thread.currentThread()); try{ for(int j=0; j< rowCount; j++ ){ Long randomTime= random.nextLong(); Date validityDate= new Date(randomTime- millisecondOf1Day), startDate= new Date(randomTime), endDate= new Date(randomTime+ 2*millisecondOf1Day); Bean bean = new Bean(); bean.setField0("K0000033"); bean.setField1("0001"); bean.setField2(sdf.format(validityDate)); bean.setField3(new Double(0.0).toString()); bean.setField4(sdf.format(startDate)); bean.setField5(sdf.format(endDate)); list.add(bean); } out.println("list is prepared in thread:"+id); Thread.sleep(millisecondOf5Min);// out.println(count+" rows has been inserted in thread:"+id); }catch (Exception e) { synchronized (out) { out.println("task:"+id+" in error"+Thread.currentThread()); e.printStackTrace(); out.println("task:"+id+" error info print completed"); } } } } } class Bean{ private String field0; private String field1; private String field2; private String field3; private String field4; private String field5; private String field6; /** * @return the field0 */ public String getField0() { return field0; } /** * @param field0 the field0 to set */ public void setField0(String field0) { this.field0 = field0; } /** * @return the field1 */ public String getField1() { return field1; } /** * @param field1 the field1 to set */ public void setField1(String field1) { this.field1 = field1; } /** * @return the field2 */ public String getField2() { return field2; } /** * @param field2 the field2 to set */ public void setField2(String field2) { this.field2 = field2; } /** * @return the field3 */ public String getField3() { return field3; } /** * @param field3 the field3 to set */ public void setField3(String field3) { this.field3 = field3; } /** * @return the field4 */ public String getField4() { return field4; } /** * @param field4 the field4 to set */ public void setField4(String field4) { this.field4 = field4; } /** * @return the field5 */ public String getField5() { return field5; } /** * @param field5 the field5 to set */ public void setField5(String field5) { this.field5 = field5; } /** * @return the field6 */ public String getField6() { return field6; } /** * @param field6 the field6 to set */ public void setField6(String field6) { this.field6 = field6; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Bean [field0=" + field0 + ", field1=" + field1 + ", field2=" + field2 + ", field3=" + field3 + ", field4=" + field4 + ", field5=" + field5 + ", field6=" + field6 + "]"; } } ``` task:1 is running! Thread[pool-1-thread-1,5,main] task:4 is running! Thread[pool-1-thread-4,5,main] task:3 is running! Thread[pool-1-thread-3,5,main] task:2 is running! Thread[pool-1-thread-2,5,main] task:5 is running! Thread[pool-1-thread-5,5,main] task:6 is running! Thread[pool-1-thread-6,5,main] all submited! task:7 is running! Thread[pool-1-thread-7,5,main] task:8 is running! Thread[pool-1-thread-8,5,main] task:7 in errorThread[pool-1-thread-7,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:7 error info print completed task:8 in errorThread[pool-1-thread-8,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:65) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:8 error info print completed task:4 in errorThread[pool-1-thread-4,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:62) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:4 error info print completed task:1 in errorThread[pool-1-thread-1,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:1 error info print completed task:5 in errorThread[pool-1-thread-5,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:65) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:5 error info print completed task:3 in errorThread[pool-1-thread-3,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:3 error info print completed task:6 in errorThread[pool-1-thread-6,5,main] java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Calendar.getDisplayName(Unknown Source) at java.text.SimpleDateFormat.subFormat(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.SimpleDateFormat.format(Unknown Source) at java.text.DateFormat.format(Unknown Source) at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) task:6 error info print completed list is prepared in thread:2
SSH2空指针异常 java.lang.NullPointerException
这个是我异常异常信息 EmployeeImpl----ID----------------->2Exception in thread "main" java.lang.NullPointerException at com.softeem.employee.dao.EmployeeImpl.findById(EmployeeImpl.java:36) at com.softeem.employee.dao.EmployeeImpl.main(EmployeeImpl.java:46) 下面是我的代码 package com.softeem.employee.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.softeem.employee.pojo.Employee; public class EmployeeImpl extends HibernateDaoSupport implements IEmployeeDAO { public Employee findById(int id) { System.out.print("EmployeeImpl----ID----------------->"+id); Employee e = (Employee) getHibernateTemplate().get(Employee.class, id); return e; } public static void main(String[] args) { EmployeeImpl ei = new EmployeeImpl(); ei.findById(2); } } 我传个值进去就报了空指针不知道怎么回事希望有人帮我下!
一个简单的学生信息管理系统,类中报错 java.lang.NullPointerException
/* * 学生类 * 姓名,学号,性别,年级,班级,总分 */ public class Student implements Comparable<Student> { private String name; private String num; private String sex; private String grade; private String banji; private String score; public Student(String name, String num, String sex, String grade, String banji, String score) { this.name = name; this.num = num; this.sex = sex; this.grade = grade; this.banji = banji; this.score = score; } public Student() { this.name = "未知"; this.num = "未知"; this.sex = "未知"; this.grade = "未知"; this.banji = "未知"; this.score = "未知"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getBanji() { return banji; } public void setBanji(String banji) { this.banji = banji; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getStudent() { return name+" "+num+" "+sex+" "+grade+" "+banji+" "+score+"\r\n"; } public int compareTo(Student other) { if (Integer.parseInt(num)<Integer.parseInt(other.num)) //学号从小到大排列 return - 1 ; if (Integer.parseInt(num)>Integer.parseInt(other.num)) return 1 ; return 0 ; } } import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Sort { private File f; public Sort(File f) { this.f = f; } public Sort() { } public List<Student> filereader() throws IOException{//对原TXT文件的读取 FileReader fr = new FileReader(f); BufferedReader cin=new BufferedReader(fr); List<Student> l=new ArrayList<Student>(); Student[] student=new Student[1000]; String s="";int i=0; while((s=cin.readLine())!=null) { student[i]=new Student(); String[] a=new String[6]; a=s.split(" "); student[i].setName(a[0]); student[i].setNum(a[1]); student[i].setSex(a[2]);; student[i].setGrade(a[3]); student[i].setBanji(a[4]); student[i].setScore(a[5]); i++; l.add(student[i]); } cin.close(); fr.close(); return l; } public void Sortsex(String sex,File f1) throws IOException{//指定性別后按学号排序 FileWriter fw = new FileWriter(f1); @SuppressWarnings("resource") BufferedWriter cout=new BufferedWriter(fw); List<Student> a=new ArrayList<Student>(); List<Student> b=new ArrayList<Student>(); a=filereader(); int i=0; Student[] student=new Student[1000]; for(int t=0;t<a.size();t++){ if(a.get(t).getSex().equals(sex)){ /*******这行报错*********/ student[i]=a.get(t); i++; } } Arrays.sort(student); for(int m=0;m<i-1;m++) { cout.write(student[i].getStudent()); } System.out.println("已生成文件"); } } Exception in thread "main" java.lang.NullPointerException at Info.main(Info.java:31)
java 空指针异常?好像逻辑有错
public class ProductsResource01 { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private ProductsService productsService; public void getProductsList(){ List<Products> list = productsService.getAll(); for(Products a : list){ System.out.println(a); } } public static void main(String[] args) { ProductsResource01 p01 = new ProductsResource01(); p01.getProductsList(); } Bug信息: Exception in thread "main" java.lang.NullPointerException at cn.syy.otherUtils.ProductsResource01.getProductsList(ProductsResource01.java:18) at cn.syy.otherUtils.ProductsResource01.main(ProductsResource01.java:26)
poi 导出 word 报错 求大神指导
poi导出到word 报错信息 Exception in thread "main" java.lang.NoSuchMethodError: org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR.getDrawingList()Ljava/util/List; at org.apache.poi.xwpf.usermodel.XWPFRun.<init>(XWPFRun.java:99) at org.apache.poi.xwpf.usermodel.XWPFParagraph.createRun(XWPFParagraph.java:272) at Test2.main(Test2.java:54) 报错代码行代码 XWPFRun r1 = p1.createRun(); 引用的jar包! [图片说明](https://img-ask.csdn.net/upload/201610/26/1477462405_111126.png)
使用fastjson,把一个JSON字符串反序列化成Map的错误。
用的fastjons的版本是: [code="java"]1.1.41[/code] json字符串如下: [code="java"] { "user_id": 5300, "flag": 0, "configs": [ { "user_id": 5300, "config_item_id": 1015, "type": 0 }, { "user_id": 5300, "config_item_id": 1016, "type": 0 } ] } [/code] 反序列化代码如下: [code="java"] HashMap jsonMap = JSON.parseObject(jsonData, HashMap.class); List<HashMap> configDataList = (List<HashMap>)jsonMap.get("configs"); for(HashMap configData : configDataList ){//这行出错 int roleId = (Integer)configData.get("type"); System.out.println("config.type:" + roleId); } [/code] 错误信息如下: [code="java"] Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to java.util.HashMap [/code] 请问,这种形式json数据,要反序列化成HashMap,该如何处理?
webmagic程序noclassdeffounderror classnotfoundexception
public class GithubRepoPageProcessor implements PageProcessor { // 抓取网站的相关配置,包括编码、抓取间隔、重试次数等 private Site site = Site.me().setRetryTimes(3).setSleepTime(100); private static int count =0; public Site getSite() { return site; } public void process(Page page) { //判断链接是否符合http://www.cnblogs.com/任意个数字字母-/p/7个数字.html格式 if(!page.getUrl().regex("http://www.cnblogs.com/[a-z 0-9 -]+/p/[0-9]{7}.html").match()){ //加入满足条件的链接 page.addTargetRequests( page.getHtml().xpath("//*[@id=\"post_list\"]/div/div[@class='post_item_body']/h3/a/@href").all()); }else{ //获取页面需要的内容 System.out.println("抓取的内容:"+ page.getHtml().xpath("//*[@id=\"Header1_HeaderTitle\"]/text()").get() ); count ++; } } public static void main(String[] args) { long startTime, endTime; System.out.println("开始爬取..."); startTime = System.currentTimeMillis(); Spider.create(new GithubRepoPageProcessor()).addUrl("https://www.cnblogs.com/").thread(5).run(); endTime = System.currentTimeMillis(); System.out.println("爬取结束,耗时约" + ((endTime - startTime) / 1000) + "秒,抓取了"+count+"条记录"); } } 输出结果: 开始爬取... Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext at us.codecraft.webmagic.Spider.initComponent(Spider.java:280) at us.codecraft.webmagic.Spider.run(Spider.java:305) at javaspider.GithubRepoPageProcessor.main(GithubRepoPageProcessor.java:38) Caused by: java.lang.ClassNotFoundException: org.apache.http.protocol.HttpContext at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 3 more
哥哥文救我!数据读出问题
public class XlsReaderDemo { static Logger logger = LoggerFactory.getLogger(XlsReaderDemo.class); private static String dataFile = "department_data.xls"; public static final String xmlConfig = "departments.xml"; public static void main(String[] args) throws IOException, SAXException, InvalidFormatException { logger.info("Running XLS Reader demo"); execute(); } public static void execute() throws IOException, SAXException, InvalidFormatException { logger.info("Reading xml config file and constructing XLSReader"); try(InputStream xmlInputStream = XlsReaderDemo.class.getResourceAsStream(xmlConfig)) { XLSReader reader = ReaderBuilder.buildFromXML(xmlInputStream); try (InputStream xlsInputStream = XlsReaderDemo.class.getResourceAsStream(dataFile)) { Department department = new Department(); Department hrDepartment = new Department(); List<Department> departments = new ArrayList<>(); Map<String, Object> beans = new HashMap<>(); beans.put("department", department); beans.put("hrDepartment", hrDepartment); beans.put("departments", departments); logger.info("Reading the data..."); reader.read(xlsInputStream, beans); logger.info("Read " + departments.size() + " departments into `departments` list"); logger.info("Read " + department.getName() + " department into `department` variable"); logger.info("Read " + hrDepartment.getHeadcount() + " employees in `hrDepartment`"); logger.info("Printing IT department employees and birthdays:"); for (Employee employee : department.getStaff()) { logger.info(employee.getName() + ": " + employee.getBirthDate()); } } } } } 错误信息16:03:55.589 [main] INFO org.jxls.demo.reader.XlsReaderDemo - Running XLS Reader demo 16:03:55.592 [main] INFO org.jxls.demo.reader.XlsReaderDemo - Reading xml config file and constructing XLSReader Exception in thread "main" java.lang.IllegalArgumentException: InputStream to parse is null at org.apache.commons.digester3.Digester.parse(Digester.java:1698) at org.jxls.reader.ReaderBuilder.buildFromXML(ReaderBuilder.java:55) at org.jxls.demo.reader.XlsReaderDemo.execute(XlsReaderDemo.java:35) at org.jxls.demo.reader.XlsReaderDemo.main(XlsReaderDemo.java:29)
关于Java多线程的问题,求大神解决
一个简单的例子,一个线程类代表客户,一个线程类代表厨师, 厨师每做好5个包子两个客户就吃,吃完再做。 运行时出现 java.lang.IllegalMonitorStateException错误,而且每次都只是一个人在吃。 实在是弄不明白了。。。 代码如下: public class Resource { //锁对象,静态资源,可以被公开访问 static Object lock = new Object(); //包子容器,静态资源,可以被公开访问 static List<String> container = new ArrayList<String>(); } public class Producer implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (true) { synchronized ("") { if (Resource.container.size() == 5) { Resource.lock.notifyAll();// 唤醒所有在等待Resource.lock这把锁的线程 } else { System.out.println("开始制作包子"); // 模拟耗时 try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Resource.container.add("包子"); } } } } } public class Cutstom implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (true) { synchronized ("") { // 容器中没有包子了,吃货们就要等待包子 if (Resource.container.size() == 0) { System.out.println("包子吃光啦,老板上包子"); try { Resource.lock.wait();// 释放自己持有了锁,并开始等待被notify } catch (InterruptedException e) { e.printStackTrace(); } } else { // 模拟耗时 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // 移除吃过的包子 System.out.println("吃货:" + Thread.currentThread().getName() + "吃包子"); Resource.container.remove(0); } } } } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Cutstom cutstom = new Cutstom() ; new Thread(cutstom,"a").start() ; new Thread(cutstom,"b").start() ; Producer producer = new Producer() ; new Thread(producer,"c").start(); } } console: Exception in thread "a" 包子吃光啦,老板上包子 java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Unknown Source) at food.Cutstom.run(Cutstom.java:15) at java.lang.Thread.run(Unknown Source) 开始制作包子 开始制作包子 开始制作包子 开始制作包子 开始制作包子 Exception in thread "c" java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method) at food.Producer.run(Producer.java:10) at java.lang.Thread.run(Unknown Source) 吃货:b吃包子 吃货:b吃包子 吃货:b吃包子 吃货:b吃包子 吃货:b吃包子 包子吃光啦,老板上包子 Exception in thread "b" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Unknown Source) at food.Cutstom.run(Cutstom.java:15) at java.lang.Thread.run(Unknown Source)
菜鸟的问题
本人第一次写android例子 环境已经全部达来了,可是总是运行部了hello world小例子,可是总是运行不起来,一看报 Still no compatible AVDs with target 'Android 1.1': Aborting launch. 按照网上的说法少avd ,于是乎敲了android list tergers ,可是有跳出了一堆异常 D:\sdk\android\tools>android list tergets Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/s dkmanager/Main (Unsupported major.minor version 49.0) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) 不知道是什么原因,哈望高手解读一下啊。
相见恨晚的超实用网站
相见恨晚的超实用网站 持续更新中。。。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
python 简易微信实现(注册登录+数据库存储+聊天+GUI+文件传输)
socket+tkinter详解+简易微信实现 历经多天的努力,查阅了许多大佬的博客后终于实现了一个简易的微信O(∩_∩)O~~ 简易数据库的实现 使用pands+CSV实现数据库框架搭建 import socket import threading from pandas import * import pymysql import csv # 创建DataFrame对象 # 存储用户数据的表(...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
JavaScript 为什么能活到现在?
作者 | 司徒正美 责编 |郭芮 出品 | CSDN(ID:CSDNnews) JavaScript能发展到现在的程度已经经历不少的坎坷,早产带来的某些缺陷是永久性的,因此浏览器才有禁用JavaScript的选项。甚至在jQuery时代有人问出这样的问题,jQuery与JavaScript哪个快?在Babel.js出来之前,发明一门全新的语言代码代替JavaScript...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
吐血推荐珍藏的Visual Studio Code插件
作为一名Java工程师,由于工作需要,最近一个月一直在写NodeJS,这种经历可以说是一部辛酸史了。好在有神器Visual Studio Code陪伴,让我的这段经历没有更加困难。眼看这段经历要告一段落了,今天就来给大家分享一下我常用的一些VSC的插件。 VSC的插件安装方法很简单,只需要点击左侧最下方的插件栏选项,然后就可以搜索你想要的插件了。 下面我们进入正题 Material Theme ...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
开源并不是你认为的那些事
点击上方蓝字 关注我们开源之道导读所以 ————想要理清开源是什么?先要厘清开源不是什么,名正言顺是句中国的古代成语,概念本身的理解非常之重要。大部分生物多样性的起源,...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Python 植物大战僵尸代码实现(2):植物卡片选择和种植
这篇文章要介绍的是: - 上方植物卡片栏的实现。 - 点击植物卡片,鼠标切换为植物图片。 - 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。
相关热词 c#中dns类 c#合并的excel c# implicit c#怎么保留3个小数点 c# 串口通信、 网络调试助手c# c# 泛型比较大小 c#解压分卷问题 c#启动居中 c# 逻辑或运算符
立即提问