0

I'm writing code for an assignment where i'm asked to convert Fahrenheit to Celsius, the other way around and store them in arrays. After doing it out and sorting the errors it showed on the side it still manages to crash after it reaches the end of the loop. I've tried doing a few things that i've seen online but nothing seems to work so far. I'm using NetBeans IDE 8.0.2

The error i get is : java.lang.StringIndexOutOfBoundsException: String index out of range: 0

The full code is :

package assignment.pkg1;

import java.util.Scanner;

public class Assignment1 {

public static void main(String[] args) 
{
 controller();
}
//----------------------------controller()--------------------------------------   
public static void controller()
{
 Scanner kb = new Scanner(System.in);
 double num[]=new double[10], cel, fah, tem;
 char ch;
 for(int x=0; x<10; x++)    //This loops ten times to get ten tempretures
    {
     System.out.print("Please enter your tempreture :");
     num[x]=kb.nextDouble();
    }

 System.out.println();
 System.out.println("Is the data you are entering in Fahrenheit or Celcius?");
 System.out.println("Please enter C for Celcius or F for Fahrenheit : ");

 ch = kb.nextLine().charAt(0);
 if (ch !='C' || ch !='c')
 {
     for(int x =0;x<10;x++)
        {
         fah=ctof(num[x]);
         System.out.println(num[x]+" degrees C = "+fah+" degrees F");
     } 
 }
 if (ch =='F' || ch =='f')
 {
     for(int x =0;x<10;x++)
        {
         cel=ftoc(num[x]);
         System.out.println(num[x]+" degrees F = "+cel+" degrees C");
  }
 }

}
//----------------------------ctog()--------------------------------------------
public static double ctof(double cel)
{
 double tem;
 //fah = cel / 5 + 32;
 tem = (cel / 5) + 32;
 return tem;
}
//----------------------------ftoc()--------------------------------------------     
    public static double ftoc(double fah)
    {
     double tem;
     //cel = (fah - 32)/9 * 5
     tem = (fah - 32) /9 * 5; 
     return tem;
    }
}
  • Usually a stacktrace is showned when an ArrayOutOfBoundException is thrown. Maybe the line number on which the exception is shown would help you find the error – D. Lawrence Nov 26 '19 at 18:05
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – azurefrog Nov 26 '19 at 18:19

2 Answers2

0

Add kb.nextLine(); in your for loop after your call to .nextDouble(); because nextDouble() does not consume the newline (\n) character.

Without doing this you are doing a charAt(0) \\ first index for an empty String, which does not have a first index.

sleepToken
  • 1,804
  • 1
  • 12
  • 21
-1

This problem is due to kb.nextDouble(); not consuming the the newline character. To fix this you could call kb.nextLine(); before ch = kb.nextLine().charAt(0);