为了账号安全,请及时绑定邮箱和手机立即绑定

如何将字符串转换为整数类型并从用户输入中输入 double 类型?

如何将字符串转换为整数类型并从用户输入中输入 double 类型?

呼啦一阵风 2021-09-12 10:48:54
/** * MadLib.java   * * @author: Jackie Hirsch * Assignment: Madlib *  * Brief Program Description: This program has will read a madlib with the inputs that the user gives the computer.  *  * */import javax.swing.JOptionPane; //import of JOptionPanepublic class MadLib{    public static void main (String[] args)    {        String cheeseType; //Cheese Character        String interjection; //interjection        String treeType; //tree type        String wholeNumberFriends; // number for number of friends on         //line 27        String numberMiles; //number of miles        int wholeNumberFriendsConverted; // number for number of         //friends on line 27 converted        double numberMilesConverted; //number of miles        //ask user for variable string cheese type        cheeseType = JOptionPane.showInputDialog ("Enter a type of         cheese");        //ask user for varaible string interjection        interjection = JOptionPane.showInputDialog ("Enter an         interjection");        //ask user for variable string tree type        treeType = JOptionPane.showInputDialog ("Enter a type of         tree");        //ask user for variable integer number for number of friends        wholeNumberFriends = JOptionPane.showInputDialog ("Enter a         whole number");        //ask user for variable double number for number of miles        numberMiles = JOptionPane.showInputDialog ("Enter a decimal or         whole number");        //string converted        wholeNumberFriends = Integer.parseInt         (wholeNumberFriendsConverted);        numberMiles = Integer.parseInt (numberMilesConverted);    }}**你好。这周我刚刚在高中计算机科学课上开始学习如何编写 Java 代码。我正在尝试将字符串转换为双精度和整数。我要转换的两个变量是 wholeNumberFriends(整数)和 numberMiles(双精度)。我为它们中的每一个都创建了一个新变量,以便它们可以轻松转换为双精度和整数。我不断收到此转换的错误是,类型不兼容: double 无法转换为 java.lang.String 。谢谢你。**
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

字符串转整数

int num = Integer.parseInt("1");

字符串加倍

double num = Double.parseDouble("1.2");


查看完整回答
反对 回复 2021-09-12
?
森林海

TA贡献2011条经验 获得超2个赞

您可以使用Integer.valueOf(java.lang.String)


       String userInput = "2";


        try {

            Integer.valueOf(userInput);

        } catch (NumberFormatException e) {

            // Not a Number

        }

同样的valueOf方法是可用的Double,Float,Long等。


该valueOf方法将返回一个对象而不是原始对象。


查看完整回答
反对 回复 2021-09-12
  • 2 回答
  • 0 关注
  • 222 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号