-2

If this has been asked before please do link the question post or somehow send it in my direction. I tried searching very hard on this site for a similar question but haven't yet to find one.

I'm doing a late assignment for my Java lvl 1 online class (yep I'm new to Java) and I think my while loop and switch statement is fine but I'm having trouble figuring out how to loop it again. The loop is supposed to go back to asking for user input. Before the user can input the next function this occurs in the console output:

This calcuclator requires you to enter a function and a number. The functions are as follows: S - Sine C - Cosine T - Tangent R - Square Root N - Natural Log X - Exit the program Enter a function: s Enter your value 40 The sine of your number is : 0.7451131604793488 S - Sine C - Cosine T - Tangent Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 R - Square Root N - Natural Log X - Exit the program Enter a function at java.lang.String.charAt(String.java:658) at assigment9.Assigment9.main(Assigment9.java:110) C:\Users\r3ds1\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 5 seconds)

Here is my Code Sample:

import java.util.Scanner;
//whileSwitch
public class Assigment9 {

    public static void main(String[] args)  {
     Scanner in = new Scanner(System.in);
     System.out.println("This calcuclator requires you to enter a function and a number.");
     System.out.println("The functions are as follows: ");

     //options
     System.out.println("S - Sine");
     System.out.println("C - Cosine");
     System.out.println("T - Tangent");
     System.out.println("R - Square Root");
     System.out.println("N - Natural Log");
     System.out.println("X - Exit the program");

     //user input
     System.out.println("Enter a function: ");
     String input = in.nextLine();
     char operation = input.charAt(0);

    //supposed to stop when user inputs 'x'
    while(!input.equals("x"))
     {

            switch(Character.toUpperCase(operation))
            {
                //Sine
            case 'S':
                System.out.println("Enter your value ");
                double s;
                double theSine;
                s = in.nextDouble();
                theSine = Math.sin(s);
                System.out.println("The sine of your number is : " + theSine );

                break;

             //Cosine
            case 'C':
                System.out.println("Enter your value ");
                double c;
                c = in.nextDouble();
                double theCosine;
                theCosine = Math.cos(c);
                System.out.println("The Cosine of your number is : " + theCosine );

                break;

            //tangent
            case 'T':
                System.out.println("Enter your value ");
                double t;
                t = in.nextDouble();
                double theTangent;
                theTangent = Math.cos(t);
                System.out.println("The Tangent of your number is : " + theTangent );

                break;

             //Square root
            case 'R':
                System.out.println("Enter your value ");
                double r;
                r = in.nextDouble();
                double theSqrt;
                theSqrt = Math.cos(r);
                System.out.println("The Square Root of your number is : " + theSqrt );

                break;

             //Natural Log
            case 'N':
                System.out.println("Enter your value ");
                double n;
                n=in.nextDouble();
                double theLog;
                theLog = Math.cos(n);
                System.out.println("The Natural Log of your number is : " + theLog );

                break;

             //Exit
            case 'X':
                System.out.println("Thanks for using this calculator. ");

                break;

            }
       //options
       System.out.println("S - Sine");
       System.out.println("C - Cosine");
       System.out.println("T - Tangent");
       System.out.println("R - Square Root");
       System.out.println("N - Natural Log");
       System.out.println("X - Exit the program");

       System.out.println("Enter a function");
       input = in.nextLine();
       operation = input.charAt(0);

     }

    }

}`

So before the user can enter the next function the program spits out a StringIndexOutOfBoundsException: String index out of range: 0. How would I fix this and an explanation of why this is occurring would be very much appreciated!

Edit:Posted all of code

second edit: corrected misinformation/ gave more.

  • What are you entering just before the error occurs? – Jim Garrison Oct 07 '16 at 04:54
  • A separate problem: `while(!input.equals("x"))` should be `while(!operation.equals("x"))` – Jim Garrison Oct 07 '16 at 04:55
  • Your code works fine for me. Could you post your input and the stack trace? You would get that error if you enter nothing, but otherwise I think it should work. – Zarwan Oct 07 '16 at 04:55
  • I think you shortened the actual problem out of the code. How do you get the value ? – ChiefTwoPencils Oct 07 '16 at 04:56
  • @JimGarrison before the error I enter one of the functions - for example 'S' for sine - program prompts user to enter a number to calculate its radians. after that it prompts for user to enter another letter for a function but when the user does so the error comes up. – Kelbin Gomez Oct 07 '16 at 04:59
  • 1
    You didn't answer my question. What letter did you enter the second time? Did you just press ENTER? – Jim Garrison Oct 07 '16 at 05:00
  • @JimGarrison nvm what i said about the the error occuring right after hitting enter before inputting a letter. it happens after I enter a value for the function. `Enter a function: s Enter your value 40 The sine of your number is : 0.7451131604793488` then soon after this happens: `Enter a function at java.lang.String.charAt(String.java:658) at assigment9.Assigment9.main(Assigment9.java:110) C:\Users\r3ds1\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 5 seconds)` – Kelbin Gomez Oct 07 '16 at 05:17
  • So edit your post and correct any incorrect information. Tell us where the error _actually_ occurs, and what the exception is. – Jim Garrison Oct 07 '16 at 05:18
  • _"then soon after..."_ -- Please explain CLEARLY. What exactly does "soon after" mean... after 1 second? After you enter a new function or before? Also, do not post extra information in comments, [edit] your post instead. – Jim Garrison Oct 07 '16 at 05:20
  • @JimGarrison edited post, happens after a second before entering a new function, and sorry about that. – Kelbin Gomez Oct 07 '16 at 05:27
  • Read that question and answer for the dup I closed this as and apply it to your code. When you take the input you're leaving a `\n` at the end which immediately gets consumed by the next `nextLine` resulting in an empty string as input and the error you see. – ChiefTwoPencils Oct 07 '16 at 05:48

4 Answers4

0

There is lower case "x" in the while condition:

while (!input.equals("x"))

Therefore the loop never really exits because of "X" input and at the end of input it reads empty string which results into the exception while reading first character from empty String.

Generally, to simplify the code, it's better to use infinite for loop:

LOOP: for (;;) {
    String input = in.nextLine();
    if (input.isEmpty()) {
        if (!in.hasNextLine())
            break;
        continue;
    }
    switch (input.characterAt(0)) {
    case 'S': ...
        ...
    case 'x':
    case 'X':
        break LOOP;
    }
}
Zbynek Vyskovsky - kvr000
  • 16,547
  • 2
  • 30
  • 40
0

Well your code works fine for me. I think that you are pressing the ENTER key after the line System.out.println("Enter a function: ");

Pressing ENTER would produce a String of length= 0, something like this
String s="";

and hence

input.charAt(0);

would produce a StringIndexOutOfBoundsException

Adit A. Pillai
  • 567
  • 1
  • 7
  • 20
0

Building off of what @Adit A. Pillai mentioned, you may want to consider adding a default to your switch, something like:

     default:
         System.out.println("Invalid input!");
         break;

You could then check for valid input prior to entering your switch:

     if (!input.equals(""))
     {
         operation = input.charAt(0);
     }

Also, if you move your menu and input code to the start of your while loop, you can avoid having to repeat those lines:

    boolean repeat = true;

    while(repeat)
    {
        System.out.println("This calcuclator requires you to enter a function and a number.");
        System.out.println("The functions are as follows: ");

        //options
        System.out.println("S - Sine");
        System.out.println("C - Cosine");
        System.out.println("T - Tangent");
        System.out.println("R - Square Root");
        System.out.println("N - Natural Log");
        System.out.println("X - Exit the program");

        //user input
        System.out.println("Enter a function: ");
        String input = in.nextLine();
        ...
    }

Note: in testing your code, I added a boolean flag to control your while loop, boolean repeat = true; which i toggled off in case 'X':

     case 'X':
         System.out.println("Thanks for using this calculator. ");
         repeat = false;
         break;

Hope this helps, keep up the coding!

andlee
  • 1
  • 3
  • ah I didn't even think about using a default case or checking for valid input :o though my problem still persists for me even though others on here aren't getting an errors running my code. I think I'll just leave it be for now with the added info you have given, thanks Andlee c: – Kelbin Gomez Oct 07 '16 at 05:50
  • @ChiefTwoPencils currently taking a look at it, thanks for posting that question link – Kelbin Gomez Oct 07 '16 at 05:57
0

I am not clear what you are exactly asking and what you are trying to do. But, Instead of Using ,

String input = in.nextLine();
char operation = input.charAt(0);

Use this,

char operation=in.next().charAt(0);
Ranjan
  • 1,214
  • 14
  • 34