用于创建对象的用户输入

时间:2017-05-21 08:19:02

标签: java string validation input

如果匹配用户输入的值,我正在尝试编写某些内容来创建特定对象。

例如:

假设我有Person类和Car类

public class Person
{
    private int x, y ,z;
    private String str;

    //Constructors etc
} 
public class Car
{
    private int x,y,z;
    private double doub;

    //Constructors etc
}

要求用户输入4个不同的值。 Person和Car的前三个字段是相同的,但如果第四个值是String或double,程序应该创建匹配对象。

public class Input
{
     public static void main (String args[])
     {
         int x,y,z;
         ?? other; //how do i declare if its either a double or string

         Scanner input = new SCanner(System.in);
         x = input.nextInt();
         // y, z input
         other = input.??? //String or double

         //Create matching object
     }
}

我该怎么做?

6 个答案:

答案 0 :(得分:3)

您可以使用4D 61 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 来检查您的输入是双精度还是字符串,例如:

matches

答案 1 :(得分:1)

您可以使用Scanner input = new Scanner(System.in); String other = input.nextLine(); if (other.matches("\\d+\\.\\d+")) { //your input is double Double d = Double.parseDouble(other); System.out.println("double = " + d); } else { //your intput is a Strings System.out.println(other); } 作为类型,使用object进行检查

instanceof

答案 2 :(得分:0)

你可以将other声明为字符串作为全局,然后检查它是否加倍,你可以将它保存在double变量中。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stickydata">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <uses-feature android:name="android.hardware.camera"
        android:required="true" />

    <uses-permission android:name="com.android.vending.BILLING" />


    <application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@drawable/sdlogo_simple"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:launchMode="singleInstance" />
        <activity
            android:name=".util.DetailActivity"
            android:label="DetailActivity" />



        <!-- BEGIN - APP CONTENT DELIVERY AND USER DATA STORAGE -->
        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

        <!--
         The following services and receivers are used to deal with transfer of
         files. If you copy and paste the user data storage or app content delivery
         feature from this sample app into your own app, make sure you include
         these items, and customize the string identifiers they use in the strings
         XML resource file.
        -->

        <service
            android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
            android:enabled="true" />
        <service android:name="com.amazonaws.mobile.downloader.service.DownloadService" />

        <receiver
            android:name="com.amazonaws.mobile.downloader.service.NetworkStateListener"
            android:enabled="false"
            android:exported="false">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

        <provider
            android:name="com.amazonaws.mobile.downloader.query.DownloadQueueProvider"
            android:authorities="@string/download_queue_provider_authority"
            android:enabled="true"
            android:exported="false" />

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

        <!-- END - APP CONTENT DELIVERY AND USER DATA STORAGE -->


        <!-- BEGIN - FACEBOOK SIGN-IN -->

        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <!-- END - FACEBOOK SIGN-IN -->

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />


    </application>

</manifest>

答案 3 :(得分:0)

使用instanceof关键字尝试此操作。

        System.out.println("Enter value");
        String userIn = new Scanner(System.in).nextLine();

        try {
            if ((Double) Double.parseDouble(userIn) instanceof Double) {
                System.out.println("Double value is entered.");
                //Write your code here if it is double
            } else if (userIn instanceof String) {
                System.out.println("String is entered");
                //Write your code here if it is String
            }
        } catch (NumberFormatException ex) {
            System.out.println("String is entered");
            //Write your code here if it is String
        }

答案 4 :(得分:0)

首先创建一个简单的String来捕获用户输入,然后尝试将其解析为double。如果它可以解析它,则意味着输入了有效的double并且不会抛出任何异常,换句话说,它将执行try块中的代码。如果它无法解析(抛出异常),它将执行catch块中的代码。

示例:

public static void main(String[] args) {

    Scanner kbd = new Scanner(System.in);
    System.out.println("Enter something...");
    String userInput = kbd.next();
    Car car = null; // create empty Car object to be able to use it outside of the try/catch block
    Person person = null; // create empty Person object to be able to use it outside of the try/catch block

    try {
        double d = Double.parseDouble(userInput);
        car = new Car();
    } catch (NumberFormatException e) {
        person = new Person();
    }

    // Ask user for new input and assign it to either Car or Person object as you develop your program...

}

答案 5 :(得分:0)

验证输入的另一种方法是使用简单的try-catch,例如:

Scanner input = new Scanner(System.in);
String other = input.nextLine();
Car car = null;
Person person = null;

try {
    // Is your input double
    Double d = Double.parseDouble(other);
    System.out.println("double = " + d);

    car = new Car();
    // ******* Write your statements to handle Car here *******

} catch (NumberFormatExaception nfe) {
    //your intput is a String
    System.out.println(other);

    person = new Person();
    // ******* Write your statements to handle Person here *******

}