如何将整数分配给字符变量,以便在 java 中输入字符串时可以对这些整数执行算术函数

How can I assign integers to character variables so that arithmetic functions can be performed on those integers when I enter a String in java

例如, 如果我分配 char A=1char B=2char C=3 等等。 然后,当我输入一个字符串时,我希望能够对分配给各个字符的各个整数值执行算术加法运算,即,我想添加我在输入字符串时分配给字符的整数值,例如,如果我输入字符串ABC 输出必须是 6 即 A+B+C.

我的代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.lang.Character;


public class AddName extends javax.swing.JFrame {


    public AddName() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Name");

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButton1.setText("Save");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButton2.setText("Back");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(41, 41, 41))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(208, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(103, 103, 103)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(124, 124, 124)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(155, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
    FrontPage fr= new FrontPage();
    fr.setVisible(true);
    dispose();// TODO add your handling code here:
    }                                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     try
        {
            String name=jTextField1.getText();
            Class.forName("com.mysql.jdbc.Driver");   //to load driver
            Connection   con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","chinu1995");//URL:path of database            
            PreparedStatement st1=con.prepareStatement("select * from NameTable where name=?");
            st1.setString(1,name);
            ResultSet rs=st1.executeQuery();

            if(rs.next())
            {
                JOptionPane.showMessageDialog(this, "Name Already Available");
            }

            else{

            PreparedStatement st=con.prepareStatement("insert  into   NameTable  values(?)");
            st.setString(1,name);
            st.executeUpdate();

            JOptionPane.showMessageDialog(this, "Name inserted successfully");
            } 
//            int sumChars(String charStr) {
//    int sum = 0;
//    for (int i = 0; i < charStr.length(); i++) {
//        sum += (charStr.charAt(i) - 'A') + 1;

//    return sum;


           //String add= jTextField1.getText();

          // for(int i=0;i<=add.length();i++){

             //int num = Character.getNumericValue(A);//charAt(0);//+add.charAt(i+1);
              //jTextField2.setText(Integer.toString(num));
         //  }



        }catch(ClassNotFoundException | SQLException e)
        {
            e.printStackTrace();//exception name+ line no

        }         // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddName.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddName.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddName.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddName.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddName().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

如果你只有大写的 A-Z,那么你可以试试这个:

int sumChars(String charStr) {
    int sum = 0;
    for (int i = 0; i < charStr.length(); i++) {
        sum += (charStr.charAt(i) - 'A') + 1;
    }
    return sum;
}

调用方式:

sumChars("ABC")

return 6

或者,如果您拥有所有的值,但它们的值不多,您可以使用 Map:

private static final Map<Character, Integer> CONST_CHAR_INT_MAP =
        Collections.unmodifiableMap(new HashMap<Character, Integer>() {{
            put('A', 1);
            put('B', 2);
            put('C', 3);
            // ...
        }});

public int charAt(char c) {
    return CONST_CHAR_INT_MAP.get(c);
}