Java: How to deal with string index out of range error? - java

I'm new to Java and I can't figure out how to solve this problem:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
Here's the entire code:
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
//Step 1: Ask user to enter first and last name
System.out.println("\nPlease enter your first and last name: ");
String name = input.nextLine();
String major = "";
String classification = "";
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
char ch = input.next().charAt(0);
char ch1 = input.nextLine().charAt(1);
//Step 3: Print statement
switch(ch) {
case 'i': major = "Information Technology"; break;
case 'c': major = "Computer Science"; break;
case 'm': major = "Mathematics"; break;
case 'p': major = "Physics"; break;
case 'b': major = "Biology"; break;
case 'e': major = "Engineering"; break;
case 'h': major = "History"; break;
case 'j': major = "Journalism"; break;
case 'a': major = "Art and Design"; break;
case 'l': major = "Literature"; break;
case 's': major = "Sport Medicine"; break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1) {
case '1': classification = "Freshman"; break;
case '2': classification = "Sophmore"; break;
case '3': classification = "Junior"; break;
case '4': classification = "Senior"; break;
case '5': classification = "Graduate"; break;
default: System.out.println("\nInvalid Classification Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
System.out.println("\nMajor and classification is: " + major + "" + classification);
System.out.println("\nThank You!");
}//end of main
Any help would be greatly appreciated.

Try to change your code so that it first checks for the length of the input before it refer to the index of the String. Something like the following:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String inputNext = input.next();
String inputNextLine;
if(inputNext.length>0 && inputNextLine.length>0){
char ch = inputNext;
char ch1 = inputNextLine;
//Step 3: Print statement
switch(ch)
{
case 'i': major = "Information Technology";
break;
case 'c': major = "Computer Science";
break;
case 'm': major = "Mathematics";
break;
case 'p': major = "Physics";
break;
case 'b': major = "Biology";
break;
case 'e': major = "Engineering";
break;
case 'h': major = "History";
break;
case 'j': major = "Journalism";
break;
case 'a': major = "Art and Design";
break;
case 'l': major = "Literature";
break;
case 's': major = "Sport Medicine";
break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1)
{
case '1': classification = "Freshman";
break;
case '2': classification = "Sophmore";
break;
case '3': classification = "Junior";
break;
case '4': classification = "Senior";
break;
case '5': classification = "Graduate";
break;
}
}

The problem is that char ch = input.next().charAt(0); will read both the characters, but not "consume" the newline character that is generated when the user hits Enter.
You then call input.nextLine(), which will consume the newline character (but now the two characters were already consumed by next(), so the resulting string is empty). Calling .charAt(1) on the empty string generates the exception because there is no position (1) in the empty string (it's length is 0).
Instead I'd suggest you use something like this:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String majorAndClassification = "";
while( majorAndClassification.length() != 2 )
majorAndClassification = input.nextLine();
char ch = majorAndClassification.charAt(0);
char ch1 = majorAndClassification.charAt(1);
This will make sure that the user enters two characters - if he doesn't, he'll have to try again until he does. A slightly better option would of course be to print out the prompt every time, like so:
//Step 2: Ask user to enter two characters
String majorAndClassification = "";
while( majorAndClassification.length() != 2 ){
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
majorAndClassification = input.nextLine();
}

If you enter the second entered character, it reads out of range because of charAt(1). Just change it to charAt(0), because you alwayws read only the first character of the input:
char ch = input.next().charAt(0);
char ch1 = input.next().charAt(0);
It works for both inputs:
i
3
And also i 3

change your code from char ch1 = input.nextLine().charAt(1);
to this char ch1 = input.next().charAt(0);
you can check this for more details about differences between next() and nextLine()

Calling
final char ch1 = input.nextLine().charAt(1);
expects a whole line to be read, and there getting the second letter.
But
char ch = input.next().charAt(0);
already consumed the first char.
So you should read the whole input in one go, then (do more checking and then) get your chars.
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
final String reply = input.nextLine();
final char ch = reply.charAt(0);
final char ch1 = reply.charAt(1);
//Step 3: Print statement

Related

How to convert certain characters in a sentence using if else statements?

my program so far only works if you enter one letter. How would I alter the program so it works with a complete sentence?
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
if(convert.equals("a")){
System.out.print("#");
}
else{
if(convert.equals("e")){
System.out.print("$");
}
An example:
Enter the string to be converted: abcde
The converted string is: #bcd$
Your program will work only for an input consisting of one character e.g. if you input a, it will print # and if you input e, it will print $ and so on (if you add other vowels too in your program). It is because you are comparing (and replacing) the whole input string rather than comparing (and replacing) the character(s) of the input string.
There are many ways in which you can do it. A couple of them are as follows:
Get an array of characters out of the input string and then iterate the array to process the printing as per your requirement e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
for (char ch : convert.toCharArray()) {
switch (ch) {
case 'a':
System.out.print('#');
break;
case 'e':
System.out.print('$');
break;
case 'i':
System.out.print('^');
break;
case 'o':
System.out.print('*');
break;
case 'u':
System.out.print('&');
break;
default:
System.out.print(ch);
}
}
}
}
A sample run:
Enter the string to be converted: coronavirus
c*r*n#v^r&s
Replace the characters as per your requirements using String::replace e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
convert = convert.replace('a', '#').replace('e', '$').replace('i', '^').replace('o', '*').replace('u', '&');
System.out.println(convert);
}
}
A sample run:
Enter the string to be converted: coronavirus
c*r*n#v^r&s
You have to add this instead of your if sentences:
for (int i = 0; i < convert.length(); i++ { //This loop will repeat the same times that the String's lenght
switch (convert.charAt(i) {
case 'a': System.out.print("#");
break;
case 'e': System.out.print("$");
break;
case 'i': System.out.print("&");
break;
case 'o': System.out.print("#"); // Here you put the letter to replace.
break;
default: // This code will execute if there's a option you didn't put on the cases
}
}

Entering character for switch statement selection

This question is regarding switch statement. These are a few similar posts on this (below) but I am still having trouble understanding.
Using user-inputted characters in If/Switch statements
How do I used a char as the case in a switch-case?
Multiple characters in a switch statement?
Please consider the following:
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
doSomething();
break;
case 2:
case 3:
default:
System.out.println("Instruction is invalid");
}
}
while (selection !=7);
{ System.exit(0); }
}
public static void showMenu()
{
System.out.print('\u000c');
System.out.println("option 1 \n");
System.out.println("option 2 \n");
System.out.println("7 - exit.\n");
System.out.println("Select Option:\n");
}
}
So this is a switch statement is for the user to choose options within the do while loop. The user enters an integer from the printed list to choose an option, after completion of the case, it loops back to menu.
My teacher informs me that its better practice to use char instead of int to get user input for the switch. I expect it to look something like this, but it doesn't work and I'm not sure why.
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
String menu = "";
char selection = menu.charAt();
switch (selection)
{
case 'A':
doSomething();
break;
case 2, 3, 4, 5, 6
default:
System.out.println("Instruction is invalid");
}
}
while (selection != 'QQ');
{ System.exit(0); }
}
In the second link posted there was an answer which i think suggested using
hello.charAt(0)
as the switch condition?
switch (hello.charAt(0))
{
case 'a': ... break;
}
I have three specific questions on this code:
1) My code doesn't work. Should my condition be hello.charAt(0) ?
2) I would like to use QQ as the quit option on the switch. Is possible with the code above? From the second link, I think it should be fine.
3) It is also shown here (switch statement using char in the case condition?) that the case statement should have double quotations. Could someone please clarify this as well?
Something like this should work better:
do {
showMenu();
String menu = in.nextLine(); // read a line of input
char selection;
if (menu.length>0) selection = menu.charAt(0); // extract the first char of the line read
else selection = '\0'; // special char when input is empty...
switch (selection) {
case 'A': case 'a':
doSomething();
break;
case 'Q': case 'q':
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
menu stores the full input line. selection would be the first char (if it exists) of the line.
To use .charAt() you need to supply the index - so if you want to use the first character then use 0, etc.
In general one read an entire line instead of a single keystroke:
The first char of a String is gotten by charAt(0). However the string
could have length 0. There is the if-expression CONDITION ? TRUEVALUE : FALSEVALUE.
String menu = in.readLine();
char selection = menu.isEmpty() ? ' ' : menu.charAt(0);
switch (selection) {
case 'A':
doSomething();
break;
case '2':
case '3':
case '4':
...
break;
default:
System.out.println("Instruction is invalid");
}
There is an even more succint solution:
String menuSelection = in.readLine();
switch (menuSelection) {
case "A":
doSomething();
break;
case "2":
case "3":
case "4":
...
break;
default:
System.out.println("Instruction is invalid");
}

the output should display a hyphen (-) after the first 3 digits and subsequently a hyphen after every 4 digits

I have an assignment but i couldn't complete this question.
Previously I add inserted else if (counter == 7) { break; } after the counter==3 but I had removed since the question said to process as many digits as the user wants.
I do not know how to add to count every 4 digit for dash after the first 3 digits dash.
the code below is what I have.
please help and explain to me if possible. thanks :)
import java.util.Scanner;
public class question1 {
public static void main (String [] args)
{
boolean notletter = false;
Scanner console = new Scanner(System.in);
String phoneletter = "";
int counter = 0;
System.out.print("Enter a phone number in letters only: ");
String phoneNumber = console.nextLine();
String phnum2 = phoneNumber.replaceAll(" ", "");
for (int i = 0; i <= phnum2.length() - 1; i++) {
if (!(Character.isLetter(phnum2.charAt(i)))) {
notletter = true;
break;
}
{
switch (Character.toUpperCase(phnum2.charAt(i))) {
case 'A':
case 'B':
case 'C':
phoneletter = phoneletter + "2";
break;
case 'D':
case 'E':
case 'F':
phoneletter = phoneletter + "3";
break;
case 'G':
case 'H':
case 'I':
phoneletter = phoneletter + "4";
break;
case 'J':
case 'K':
case 'L':
phoneletter = phoneletter + "5";
break;
case 'M':
case 'N':
case 'O':
phoneletter = phoneletter + "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
phoneletter = phoneletter + "7";
break;
case 'T':
case 'U':
case 'V':
phoneletter = phoneletter + "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
phoneletter = phoneletter + "9";
break;
}
counter++;
if (counter ==3) {
phoneletter = phoneletter + "-";
}
}
}
if (notletter == true) {
System.out.println("Please indicate only alphabets");
} else {
System.out.println(phoneletter);
}
}
}
This can be done by editing the if-statement at the end of your code:
if (counter ==3) {
phoneletter = phoneletter + "-";
}
Here you already checked if the counter is three. If it is, add a hyphen. The next thing to do is to check the case of "a hyphen after every 4 digits". To do this, we can check if counter - 3 is a multiple of 4:
(counter - 3) % 4 == 0
However, this would make it insert an extra - at the end of the output if (input length - 1) is a multiple of 4. So we shouldn't add a hyphen if we reached the end of the string. This can be done by checking whether i is phnom.length() - 1:
i != phnom.length() - 1
If we combine all these conditions together, we get
if (counter == 3 || ((counter - 3) % 4 == 0 && i != phnom.length() - 1)) {
Note: This can actually be done using a regular expression, but since this is homework, I doubt this approach will be accepted. Here is how you do this with regex:
// phoneLetter is a string of digits without any hyphens
String result = phoneLetter.replaceAll("^\\d{3}|\\d{4}(?!$)", "$0-");

Problems at detecting spacebars at Strings

So I'm doing a program that takes a user input and when it finds chars that are similar to numbers, it replaces it by the number. (For example, it replaces O's by 0's, e's by 3's, etc) The problem is that when it finds a blank space it all messes up. You can check by compiling the code that the output is completely messed up.
/* Program to encrypt text replacing some letters by similar numbers
Done by: Gabriel Mello
*/
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String input; //Allocating space for user input
char[] output=new char[100000]; //Allocating space for final output
while(true){ // Lets it work as many times as wished
System.out.println("EscribĂ­ la frase que quieras transformar"); // Spanish for input your frase
input=sc.next(); //Takes user input
for(int i=0; i<=input.length()-1;i++){ //Iterates over every char in the input
switch(input.charAt(i)){//Checks wether the current digit is valid for replacement,
case 'O': // if it is, it replaces it, if not, it leaves it as it is.
case 'o': output[i]='0';
break;
case 'L':
case 'l':
case 'I':
case 'i': output[i]='1';
break;
case 'Z':
case 'z': output[i]='2';
break;
case 'E':
case 'e': output[i]='3';
break;
case 'A':
case 'a': output[i]='4';
break;
case 'S':
case 's': output[i]='5';
break;
case 'G':
case 'g': output[i]='6';
break;
case 'T':
case 't': output[i]='7';
break;
case 'B':
case 'b': output[i]='8';
break;
case 'P':
case 'p': output[i]='9';
break;
default: output[i]=input.charAt(i);
}
}
System.out.println(output); //Prints the output
for(int i=0;i<=output.length-1;i++){ //Resets the output array
output[i]=' ';
}
}
}
}
The Scanner input splits at spaces. So if you type in 12 34 the first input your code sees is 12. It Runs through the for(int i=0; i<=input.length()-1;i++) loop, then the while loop finds another input 34 and again runs through it. See the Java doc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Replace input=sc.next() by input=sc.nextLine() to fix it.

Using throws java.io.IOException and getting System.in.read(); to access a case via an integer

I only need help with the input part. If the user inputs a number I need the program to read and output a case that equals the number that was input.
//This program will display the months of the year
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
int month;
System.out.println("Please enter a Month Number: ");
month = (int) System.in.read(); //Get an integer
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Try using the Console class instead: http://docs.oracle.com/javase/6/docs/api/java/io/Console.html to obtain user input, then convert the String to a number with Integer.parseInt(String)
Also, be aware that the next version of Java (8) will support Strings in case blocks.
class vehicle
{
int passengers;
int fuelcap;
int mpg;
}
import java.io.*;
class Vehicle_Demo
{
public static void main (String args[]) throws java.io.IOException
{
vehicle obj1 = new vehicle();
obj1.passengers=12;
obj1.fuelcap=9;
obj1.mpg=78;
System.out.println(obj1.passengers, obj1.fuelcap, obj1.mpg);
}
}
You can use Scanner to read your System.in
Scanner input = new Scanner(System.in);
month = input.nextInt();
Output:
Please enter a Month Number:
1
January
See related
Edit:
as noahz pointed out there is a Console class that covers the same functionality. For an idea of the difference between the two, read this.
Try to use TextIO Input Functions
This is better than scanner input
You need to compile TextIO.java fist as a prerequisite so that TextIO.class must be found in the same folder.
use this input function instead:
month = TextIO.getChar();
Please let me know if you have problems on this method.
Thanks!
Correct me if I'm wrong, but I'm pretty sure it will still work with "system.in.read". You're switch cases do not have single quotes around the input you want to be processed. If you want case one to be run when you type '1' your case should be case '1', not case 1.
There problem here was Java have cast a character to an integer, therefore you get an ASCII value.
For instance, when you type 5 you've got 53 in ASCII. Check it taking the variable value in System.out.println();
I've tried to solve that changing month to a char type and then passing a char value to the switch control. But the problem is, getting System.in.read(); method you just can get a single character. At last you just can select between 1 to 9.
I suspect the solution is using a buffer reader. Until then, I leave you here my code:
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
char month;
System.out.println("Please enter a Month Number: ");
month = (char) System.in.read(); //Get an integer
//System.out.println("Actual value of :" + month);
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
/*case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;*/
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}

Categories

Resources