InputMismatchException when scanning

78 views Asked by At

I'm doing an assignment trying to manipulate an array of ints (grades). It's crashing and I can't figure out why. I don't know if it has something to do with the file input, output? the error log seems to be saying it isn't even getting past running the method onclick.

main activity code:

package com.example.brandon.lab5;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import android.content.res.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @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);
    }

    public void arrayChange(View view)
        throws IOException {
            EditText et;
            TextView tv;
            String fileName;
            tv = (TextView) findViewById(R.id.text_main);
            et = (EditText) findViewById(R.id.edit_infile);
            int n=0;

            AssetManager assetManager = getAssets();
            fileName = (et.getText().toString());
            Scanner fsc = new Scanner(assetManager.open(fileName));
            int grades[] = new int[100];
            while(fsc.hasNext()) {
                grades[n] = fsc.nextInt();
                n++;
            }
            int fromIndex = 0;
            int toIndex = grades.length;
            int size = grades.length;

            double cubicMean = 0;
            double num = 0;
            double deno = size;
            while(size>0) {
                num+=Math.pow(grades[size], 3);
                size--;
            }
            cubicMean = Math.cbrt((num/deno));

            Arrays.sort(grades, fromIndex, toIndex);

            double med = 0;
            double temp = Math.ceil(grades[(toIndex/2)]);
            if(toIndex%2==0) {
                med = ((grades[toIndex/2] + grades[(toIndex/2)+1])/2);
            }
            else {
                med = temp;
            }

            tv.append("Number of grades: " + grades.length);
            tv.append("Highest grade: " + grades[0]);
            tv.append("Cubed root of the grades: " + cubicMean);
            tv.append("Median grade: " + med);

            File outfile = new File(getExternalFilesDir(null), "out.txt");
            FileWriter fw = new FileWriter(outfile);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            while(size>0) {
                pw.println(grades[size]);
                size--;
            }
            pw.close();
        }
    }

manifest

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

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application

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

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

XML

<?xml version="1.0" encoding="utf-8"?>

<!-- your context in the "tools:context" field below.  See YYY -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.brandon.lab5.MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/edit_infile"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="@string/edit_infile" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="arrayChange"
        android:text="Start" />

    <!-- Spacing and horizontal rule (line) to separate Button from TextView -->

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="0.5dp"
        android:background="#000000" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/text_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="..." />

    </ScrollView>

</LinearLayout>

logcat:

       --------- beginning of crash
12-04 23:16:22.456 3056-3056/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.brandon.lab5, PID: 3056
                                                 java.lang.IllegalStateException: Could not execute method for android:onClick
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.lang.reflect.InvocationTargetException
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                     at android.view.View.performClick(View.java:4780) 
                                                     at android.view.View$PerformClick.run(View.java:19866) 
                                                     at android.os.Handler.handleCallback(Handler.java:739) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                     at android.os.Looper.loop(Looper.java:135) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
                                                  Caused by: java.util.InputMismatchException
                                                     at java.util.Scanner.next(Scanner.java:973)
                                                     at java.util.Scanner.nextInt(Scanner.java:1318)
                                                     at java.util.Scanner.nextInt(Scanner.java:1282)
                                                     at com.example.brandon.lab5.MainActivity.arrayChange(MainActivity.java:72)
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                     at android.view.View.performClick(View.java:4780) 
                                                     at android.view.View$PerformClick.run(View.java:19866) 
                                                     at android.os.Handler.handleCallback(Handler.java:739) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                     at android.os.Looper.loop(Looper.java:135) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
12-04 23:16:22.457 1514-1646/system_process W/ActivityManager: 
1

There are 1 answers

0
azizbekian On

Here's the problematic code:


    while(fsc.hasNext()) {
        grades[n] = fsc.nextInt();
        n++;
    }

From the docs of Scanner#nextInt():

Throws

InputMismatchException if the next token does not match the Integer regular expression, or is out of range

Double-check your file content.