1

Hope this is appropriate format for a question. Im just trying to do a basic calculator type program that receives a unit value and numeric value from the user, out puts the result, and asks them if they want to do another calculation.

My knee jerk reaction was to go for a do while loop so the program would be executed at least once before prompting the user if they wanted to try again.

The program runs through the first loop fine, but crashes on the second run through if the user wants to play again.

Displaying this strange thing which I dont fully understand "play again? n Enter a temperature unit (c for Celsius and f for Fahrenheit): Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:1512) at temp3.main(temp3.java:19"

The program goes like this:

import java.util.Scanner;

public class temp3 {
    
    public static void main(String[] args){

        
        Scanner stdin = new Scanner(System.in);
        char unit;
        double temp;
        char cont;
        char choice;
        char a;

        
        
        do {
            System.out.print("Enter a temperature unit (c for Celsius and f for Fahrenheit): ");
       unit = stdin.nextLine().charAt(0);

       System.out.print("Enter a temperature degree(e.g., 35.5): ");
       temp = stdin.nextDouble();

        if (unit == 'c' || unit == 'C'){
       System.out.print(temp * 2);
      
       } else if (unit == 'f' || unit == 'F') {
       System.out.print(temp * 3); //convert Fahrenheit to celsius
       }
       else{
       System.out.println("Invalid temperature unit");
       }
    
       System.out.println("play again?"); 
       a = stdin.next().charAt(0);
       
       
       
   }
   

while ( a == 'n' );
        
        
        
       
}
}   
Joe5701
  • 11
  • 1
  • Diddn't have time to answer, sorry: Multiple issues: 1/ You're doing a `nextLine()` on your first call, when you likely want just a `next()`. 2/ Your exit condition is strange: you ask if someone wants to play again, but if they type 'n' (for **no**?) then... you continue :) Probably want to say `while (a == 'y')` or `while (a != 'n')` – haylem Oct 15 '21 at 16:31
  • haylem thank you so much! However long it took you to write that out saved me probably hours of a head ache. The nextLine() thing was what was throwing me for a loop. – Joe5701 Oct 15 '21 at 16:43
  • Can't say I know exactly what that changed, but finding out that issue definitely gives me a place to direct my learning. Thanks again. – Joe5701 Oct 15 '21 at 16:47

0 Answers0