当前位置: 代码迷 >> java >> 如何将其更改为字符串而不是整数
  详细解决方案

如何将其更改为字符串而不是整数

热度:57   发布时间:2023-07-18 08:59:09.0
import java.awt.*;
import javax.swing.*;
public class Drawing extstrong textends JApplet{
    int choice;

    public void init(){
        String input;
        input=JOptionPane.showInputDialog(
              "Enter 1 to draw lines\n"+
              "Enter 2 to draw squares\n"+
              "Enter 3 to draw circles\n");
        choice=Integer.parseInt(input);
    }/* how to change it to string like key in line square and circle not 1,2,3*/

    public void paint(Graphics g){
        int[] x = {300,293,276,250,217,183,151,124,107,101,107,124,150,183,217,249,276,293};
        int[] y = {200,234,264,286,298,298,286,264,234,200,166,136,114,102,102,114,136,166};

        for(int i=0; i<18; i++){
            if( choice == 1 ){
                g.drawLine(200,200,x[i],y[i]);}
            else if( choice == 2 ){
                g.drawRect(x[i],y[i],100,100);}
            else{
                g.drawOval(x[i],y[i],100,100);}
        }
    }
}

如果我理解正确,您希望用户输入单词(字符串)而不是使用数字来做出选择。 比您可以这样尝试:

public class Drawing extstrong textends JApplet{
  int choice;

  public void init(){
    String input;
    input=JOptionPane.showInputDialog(
          "Enter \"lines\" to draw lines\n"+
          "Enter \"squares\" to draw squares\n"+
          "Enter anything else to draw circles\n");
    choice = input;
  }/* how to change it to string like key in line square and circle not 1,2,3*/`how to change`

  public void paint(Graphics g){
    int[] x = {300,293,276,250,217,183,151,124,107,101,107,124,150,183,217,249,276,293};
    int[] y = {200,234,264,286,298,298,286,264,234,200,166,136,114,102,102,114,136,166};

      for(int i=0; i<18; i++){
        if( choice.equals("lines") ){
           g.drawLine(200,200,x[i],y[i]);}
        else if( choice.equals("squares") ){
           g.drawRect(x[i],y[i],100,100);}
        else{
           g.drawOval(x[i],y[i],100,100);}
      }
  }

}

public class Drawing extends JApplet{
  String choice;

  public void init(){
    String input;
    input=JOptionPane.showInputDialog(
          "Enter line to draw lines\n"+
          "Enter square to draw squares\n"+
          "Enter circle to draw circles\n");
    //choice=Integer.parseInt(input);
    choice=input;
  }

  public void paint(Graphics g){
    int[] x = {300,293,276,250,217,183,151,124,107,101,107,124,150,183,217,249,276,293};
    int[] y = {200,234,264,286,298,298,286,264,234,200,166,136,114,102,102,114,136,166};

      for(int i=0; i<18; i++){
        if( choice .equals("line") ){
           g.drawLine(200,200,x[i],y[i]);}
        else if(choice .equals("square") ){
           g.drawRect(x[i],y[i],100,100);}
        else{
           g.drawOval(x[i],y[i],100,100);}
      }
  }}
  相关解决方案