将字符串从语音转换为双精度

时间:2015-02-12 20:46:38

标签: java android

我想创建一个可以逐个询问用户2个号码的应用。 然后将它们相乘并告诉用户结果。 但是当我尝试将用户的语音字符串转换为double时,我的应用程序崩溃了。 这是我的代码:

num1 = Double.parseDouble(String.valueOf(matches));

(num1是double,match是用户语音的字符串形式) 如果你需要更多代码,请告诉我。 提前谢谢!

编辑:这是整个活动_

package cannon.gaming.physicsdroidvoice;

import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MainActivity extends ActionBarActivity {
    private SpeechRecognizer mSpeechRecognizer;
    private Intent mSpeechRecognizerIntent;
    private boolean mIslistening;
    int forza, m, a;
    double mass, acc, mares;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);
        forza = 0;
        m = 0;
        mass = 0;
        a = 0;
        acc = 0;
        mares = 0;
        final String abc = "Welcome to PhysicsDroid!";
        final String abcc = "What do you need?";
        final String abccc = "Force, Velocity, Mass, Acceleration, Distance, Time, Temperature, Work, Density, Info, or Exit?";
        final String abcccc = "Just tap the screen and speak. When you are done, tap the screen again.";
        final String abccccc = "Can you repeat please?";
        final String force = "Which force equation would you like to use?";
        final String exit = "Thank you for using PhysicsDroid, see ya!";
        final String one = "First one: F=m times A. Second one: F=p times A. Or third one: Fg=G times m1m2 over r squared?";
        final String ma = "What is the mass of object in kilograms?";
        final String am = "What is the acceleration of object in meters per second squared?";
        final String mnum = "What the...!";
        final TextToSpeech home = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                   //DO NOTHING
                }
            }
        });
        new Timer().schedule(
                new TimerTask() {
                    @Override
                    public void run()
                    {
                            home.speak(abc, TextToSpeech.QUEUE_ADD, null);
                            home.speak(abcc, TextToSpeech.QUEUE_ADD, null);
                            home.speak(abccc, TextToSpeech.QUEUE_ADD, null);
                            home.speak(abcccc, TextToSpeech.QUEUE_ADD, null);
                    }
                },
                1000
        );
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
        this.getPackageName());
        class SpeechRecognitionListener implements RecognitionListener
        {

            @Override
            public void onBeginningOfSpeech()
            {
                //Log.d(TAG, "onBeginingOfSpeech");
            }

            @Override
            public void onBufferReceived(byte[] buffer)
            {

            }

            @Override
            public void onEndOfSpeech()
            {
                //Log.d(TAG, "onEndOfSpeech");
            }

            @Override
            public void onError(int error)
            {

                //Log.d(TAG, "error = " + error);
            }

            @Override
            public void onEvent(int eventType, Bundle params)
            {

            }

            @Override
            public void onPartialResults(Bundle partialResults)
            {

            }

            @Override
            public void onReadyForSpeech(Bundle params)
            {
                //Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
            }

            @Override
            public void onResults(Bundle results)
            {
                //Log.d(TAG, "onResults"); //$NON-NLS-1$
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                CharSequence cs1 = "Force";
                CharSequence cs2 = "force";
                CharSequence cs3 = "Exit";
                CharSequence cs4 = "exit";
                CharSequence cs5 = "First";
                CharSequence cs6 = "first";
                CharSequence cs7 = "times";
                CharSequence cs8 = "equals";
                Pattern p = Pattern.compile("[a-zA-Z]");
                Matcher mat = p.matcher("3453443534534");
                if(forza == 1 && m == 0 && a == 0)
                {
                    if(String.valueOf(matches).contains(cs5) || String.valueOf(matches).contains(cs6) || String.valueOf(matches).contains(cs7) || String.valueOf(matches).contains(cs8))
                    {
                        home.speak(ma,TextToSpeech.QUEUE_FLUSH, null);
                        forza = 0;
                        m = 1;
                    }
                }
                else if(m == 1 && forza == 0 && a == 0)
                {
                    if(String.valueOf(matches).matches(".*\\d.*"))
                    {
                        mass = Double.parseDouble(String.valueOf(matches));
                        home.speak(am,TextToSpeech.QUEUE_FLUSH, null);
                        m = 0;
                        a = 1;
                        home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
                    }
                    else
                    {
                        home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
                else if(a == 1 && m == 0 && forza == 0)
                {
                    if(String.valueOf(matches).contains("[a-zA-Z]+") || String.valueOf(matches).equals("") || String.valueOf(matches).equals(".") || String.valueOf(matches).equals("-.") || String.valueOf(matches).equals("-"))
                    {
                        home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
                    }
                    else
                    {
                        acc = Double.parseDouble(String.valueOf(matches));
                        a = 0;
                        mares = mass * acc;
                        String mare = String.format("The force is %d", mares);
                        home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
                    }
                }
                else if(String.valueOf(matches).contains(cs1) || String.valueOf(matches).contains(cs2) && forza == 0 && m == 0 && a == 0)
                {
                    home.speak(force,TextToSpeech.QUEUE_FLUSH, null);
                    home.speak(one,TextToSpeech.QUEUE_ADD, null);
                    forza = 1;
                }
                else if(String.valueOf(matches).contains(cs3) || String.valueOf(matches).contains(cs4) && forza == 0 && m == 0 && a == 0)
                {
                    home.speak(exit,TextToSpeech.QUEUE_FLUSH, null);
                    new Timer().schedule(
                            new TimerTask() {
                                @Override
                                public void run() {
                                    android.os.Process.killProcess(android.os.Process.myPid());
                                    System.exit(1);
                                }
                            },
                            4000
                    );
                }
                else
                {
                    home.speak(abccccc,TextToSpeech.QUEUE_FLUSH, null);
                }
                // matches are the return values of speech recognition engine
                // Use these values for whatever you wish to do
            }

            @Override
            public void onRmsChanged(float rmsdB)
            {

            }

        }
        SpeechRecognitionListener listener = new SpeechRecognitionListener();
        mSpeechRecognizer.setRecognitionListener(listener);
        RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.MainActivity);
        rlayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)
            {
                boolean mIsListening = false;
                if (!mIsListening)
                {
                    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                }

                else
                {
                    mSpeechRecognizer.cancel();
                }
            }

        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

确保匹配不为null或者为double。

您可以使用try catch来检查匹配项是否是运行时的数字。如果matches是一个字符串,你也不应该需要String.valueOf。

try {
  num1 = Double.parseDouble(matches);

} catch (NumberFormatException e) {
    e.pritStackTrace();
}

还要确保num1已初始化。