Absolute beginner here. I'm taking an introductory class to programming using Java and I've already fallen behind. The professor seems to just "do" in class and not really instruct. He also gives us examples to programs and then assigns programs that are far more complex than what he showed us in class.
I took it upon myself to start over and read the textbook page by page, and sure enough, many of the things I did not initially understand make sense now, and most of the programs that wouldn't work before now do.
Nevertheless, I'm stuck in the section called "Reading Keyboard Input," to be more specific, "Reading a Character." The book explains that the Scanner class does not have a method to read a single character, therefore the nextLine method is used to read a string from the keyboard, you enter a single letter, then the charAt method is used to extract the first character of the string.
The book explains it step by step, so I added the new lines to an already existing program called Payroll.java, and the original program works, but it won't let me input anything after the new lines are printed.
import java.util.Scanner; //Needed for the Scanner class
/**
* This program demonstrates the Scanner class.
*/
public class Payroll{
public static void main(String[] args){
String name; //To hold a name
int hours; //Hours worked
double payRate; //Hourly pay rate
double grossPay; //Gross pay
String input; //To hold a line of input
char answer; //To hold a single character
//Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
System.out.print("What is your name? ");
name = keyboard.nextLine();
//Get the number of hours worked this week.
System.out.print("How many hours did you work this week? ");
hours = keyboard.nextInt();
//Get the user's hourly pay rate.
System.out.print("What is your hourly pay rate? ");
payRate = keyboard.nextDouble();
//Calculate the gross pay.
grossPay = hours * payRate;
// Ask the user a question.
System.out.print("Are you having fun? (Y=yes, N=no) ");
input = keyboard.nextLine(); // Get a line of input.
answer = input.charAt(0); // Get the first character.
}
}
The error I get is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String >index out of range: 0 at java.lang.String.charAt(Unknown Source) at Payroll.main(Payroll.java:39)