2016-10-18 3 views
0

Я пытаюсь сделать приложение калькулятора. Сначала я создал класс, который возьмет строку (мое уравнение для решения) и изменит ее с Infix на Postfix. Приложение буквально несет кости, но когда я его запускаю, он немедленно сбой, и в консоли я не получаю ошибки. Как любая идея, где может быть проблема?Сбой приложения Android при запуске

Файл манифеста:

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

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

XML файл activity_main:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="com.example.android.projectcalculator.MainActivity"> 

    <TextView 
     android:id="@+id/textCalc" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:padding="10sp" 
     android:layout_weight="1" 
     android:text="Hello"/> 
</LinearLayout> 

Java-файл MainActivity:

package com.example.android.projectcalculator; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.TextView; 
import static android.R.attr.onClick; 

import com.example.android.projectcalculator.InfixToPostfix; 

public class MainActivity extends AppCompatActivity { 

    public TextView calculationText; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     PrintMainScreen("hello you"); 
     String s = InfixToPostfix.StartInfixToPostfix("A*(B+C)"); 
     PrintMainScreen(s); 
    } 

    public void PrintMainScreen(String str) 
    { 
     TextView txview = (TextView)findViewById(R.id.textCalc); 
     txview.setText(str); 
    } 
} 

Java-файл InfiToPostfix:

package com.example.android.projectcalculator; 

import java.util.Stack; 

public class InfixToPostfix{ 

    //Varibili private 
    private static String postfixOutput; 
    private static Stack<Character> operatorStack; 
    private static String infixInput; 

    //Metodo per controlare se ho a che fare con l'operatore 
    private static boolean IsOperator (char c) 
    { 
     return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c == '^'; 
    } 

    private static int OpratorPriority(Character operator1) 
    { 
     switch(operator1) 
     { 
      case '+': 
      case '-': 
       return 1; 
      case '*': 
      case '/': 
       return 2; 
      case '^': 
       return 3; 
      default: 
       return 0; 
     } 
    } 

    //Metodo Supremo 
    public static String StartInfixToPostfix(String in) 
    { 
     //inizializzo variabili 
     postfixOutput = ""; 
     infixInput.equals(in); 
     int lunghezza = infixInput.length(); 
     operatorStack = new Stack<Character>(); 

     //inizio il processo 
     for (int i=0; i < infixInput.length(); i++) 
     { 
      //se non è un operatore ma un operando, lo aggiungo alla string di output 
      if (!IsOperator(infixInput.charAt(i))) 
      { 
       postfixOutput += infixInput.charAt(i); 
      } 
      //Considero il caso in cui sia l'operatore ')' 
      else if (infixInput.charAt(i) == ')') 
      { 
       //Inserisco nel postfix gli operatori fino a che lo sctack è vuoto o incontro una parentesi chiusa 
       while (!operatorStack.isEmpty() && operatorStack.peek() != ')') 
       { 
        postfixOutput += (operatorStack.pop()); 
       } 
       //elimino la '(' se c'è 
       if (!operatorStack.isEmpty()) 
       { 
        operatorStack.pop(); 
       } 
      } 
      //considero il caso in cui ho un operatore che non sia ')' 
      else 
      { 
       //questo while si attiva solo se (1) lo stack non è vuoto (2) l'elemento in cima allo stack non è '(' (3) se l'ultimo operatore ha grado minore 
       while ((!operatorStack.isEmpty()) && (operatorStack.peek() != '(') && (OpratorPriority(operatorStack.peek()) >= OpratorPriority(infixInput.charAt(i)))) 
       { 
        postfixOutput += operatorStack.pop(); 
       } 
       //aggiungo l'operatore a prescindere di ciò che ho fatto o non fatto con il cilo while 
       operatorStack.push(infixInput.charAt(i)); 
      } 
     } 

     //Alla fine del metodo rilascio il postfix 
     return postfixOutput; 
    } 
} 

Редактировать: Кто-нибудь знает, почему я получаю сообщение об ошибке, если все в классе InfixToPostfix не является статическим?

Edit2: Теперь дает мне эту ошибку ...

E/AndroidRuntime: FATAL EXCEPTION: main 
        Process: com.example.android.projectcalculator, PID: 25981 
        Theme: themes:{} 
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.projectcalculator/com.example.android.projectcalculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510) 
         at android.app.ActivityThread.-wrap11(ActivityThread.java) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:148) 
         at android.app.ActivityThread.main(ActivityThread.java:5461) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference 
         at com.example.android.projectcalculator.InfixToPostfix.StartInfixToPostfix(InfixToPostfix.java:40) 
         at com.example.android.projectcalculator.MainActivity.onCreate(MainActivity.java:20) 
         at android.app.Activity.performCreate(Activity.java:6251) 
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)  
         at android.app.ActivityThread.-wrap11(ActivityThread.java)  
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)  
         at android.os.Handler.dispatchMessage(Handler.java:102)  
         at android.os.Looper.loop(Looper.java:148)  
         at android.app.ActivityThread.main(ActivityThread.java:5461)  
         at java.lang.reflect.Method.invoke(Native Method)  
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  
+0

Если вы говорите об аварии, тогда должен быть журнал, который вы должны отправить. Код активности выглядит нормально – Raghunandan

+0

'infixInput' равно null. – Michael

+0

Клянусь, что консоль не дала мне никаких ошибок первые 3 или 4 раза ... Теперь это дает мне эти ошибки. –

ответ

1

ваш infixInput в строке 40 равна нулю, поскольку он не инициализируется

+0

В первую очередь я объявляю 'infixInput.equal (in);' –

+0

Не проверяйте это значение, если 'infixInput' имеет такое же значение, как' in'. Он ничего не инициализирует! – HelloSadness

+0

О мой! Благодаря! Теперь это довольно ясно –

1

вы должны инициализировать переменную infixInput.

private static String infixInput = ""; 

Кроме того, кажется, что вы хотели инициализировать infixInput с in значением. Выполнение infixInput.equals(in) просто проверьте, сохраняют ли обе переменные одинаковое значение и возвращают логическое значение.

Тогда вы должны сделать:

infixInput = in.toString() 
1

infixInput.equals(in); является NULL. Сначала необходимо инициализировать infixInput.

String.equals(String) проверяет, равно ли содержание обеих строк. Это не работает, если одна из строк имеет значение NULL.

Смежные вопросы