String index out of range error 7 [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String index out of range: n
I'm writing a program to generate a username based off of a user's inputs (first, middle, and last names). I'm supposed to get the first character from each name(first, middle, and last) as well as the last character of the last name in order to generate a username. I've successfully wrote the program to generate the first character of each name, but when I tried to get my program to generate the last character of the last name I would get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.charAt(String.java:658)
at UsernameGenerator.main(UsernameGenerator.java:39)
Here is my code:
import java.util.Scanner;
/**
UsernameGenerator.java
Generates a username based on the users inputs.
#author: Evan Fravert
*/
public class UsernameGenerator {
/**
* Generates a username based on the users inputs.
*#param args command line argument
*/
public static void main(String[] args)
{ // abcde
String first;
String middle;
String last;
String password1;
String password2;
int randomNum;
randomNum = (int) (Math.random() * 1000) + 100;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your first name:");
first = userInput.nextLine();
String firstLower = first.toLowerCase();
System.out.println("Please enter your middle name:");
middle = userInput.nextLine();
String middleLower = middle.toLowerCase();
System.out.println("Please enter your last name:");
last = userInput.nextLine();
int lastEnd = last.length();
String lastLower = last.toLowerCase();
System.out.println("Please enter your password:");
password1 = userInput.nextLine();
System.out.println("Please enter your password again:");
password2 = userInput.nextLine();
char firstLetter = firstLower.charAt(0);
char middleLetter = middleLower.charAt(0);
char lastLetter = lastLower.charAt(0);
char lastLast = lastLower.charAt(lastEnd);
if (first == null || first.length() <= 0) {
firstLetter = 'z';
}
else {
firstLetter = firstLower.charAt(0);
}
System.out.println("Your username is " + firstLetter + ""
+ middleLetter + "" + lastLetter + "" + "" + lastLast + "" + randomNum);
System.out.println("Your password is " + password1);
System.out.println("Welcome " + first + " " + middle + " " + last + "!");
}
}
Thanks in advance!

Java arrays are zero based, the last index is last.length() - 1

Try this:
char lastLast = lastLower.charAt(lastEnd-1);

Related

LAB: Login name. Error with printing an entire string if it’s over a certain number of characters

I'm working on this lab:
Write a program that creates a login name for a user, given the user's first name, last name, and a four-digit integer as input. Output the login name, which is made up of the first five letters of the last name, followed by the first letter of the first name, and then the last two digits of the number (use the % operator). If the last name has less than five letters, then use all letters of the last name.
I have a code that works for input where the last name is five letters or more, but am confused on how to add the part where there is a last name with less than five letters. Do I use an if statement?
Here is my code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userFirstName;
String userLastName;
int birthYear;
String loginName;
userFirstName = scnr.next();
userLastName = scnr.next();
birthYear = scnr.nextInt();
loginName = userLastName.substring(0,4);
loginName = loginName + userFirstName.charAt(0);
loginName = loginName + (birthYear % 100) ;
System.out.println("Your login name: " + loginName);
}
}
Do I use an if statement?
Yes
Over here:
loginName = userLastName.substring(0,4);
loginName = loginName + userFirstName.charAt(0);
loginName = loginName + (birthYear % 100) ;
You can simply add
if (userLastName.length()<5)
loginName = userLastName;
//this will initialize loginName with all the characters available
else
loginName = userLastName.substring(0,4);
/*
in my opinion this will return only 4 characters and not the fifth one
If that's the case, make the .substring(0,5);
*/
loginName = loginName + userFirstName.charAt(0);
loginName = loginName + (birthYear % 100) ;

Beginning coder (Java) - validating String input and ending a loop once correct input has been entered

The idea with this question is that the user knows to input the sentence "Robin came to Montreal, Canada in 2009.". From there, the code should spit back "Robin stays in Montreal, for 11 years. Montreal is in Canada. Please enter the input sentence (press q to exit):".
I've managed to get a loop going so that as long as the user is inputting the sentence correctly the program will also spit back the correct phrase. The part that I'm struggling with is ending the loop - getting "q" to terminate the program. Instead I get an error. Please let me know what I can do.
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MiniTranslator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String sentence;
do {
System.out.println("Please enter the input sentence (press q to exit)");
sentence = scan.nextLine();
int i = sentence.indexOf(' ');
String word = sentence.substring(0, i);
String sentence2 = sentence.substring(i + 9, sentence.length());
int j = sentence2.indexOf(' ');
String word2 = sentence2.substring(0, j);
Matcher matcher = Pattern.compile("\\d+").matcher(sentence);
matcher.find();
int k = Integer.valueOf(matcher.group());
String sentence3 = sentence2.substring(j + 1, sentence2.length());
int l = sentence3.indexOf(' ');
String word3 = sentence3.substring(0, l);
System.out.println(word + " stays in " + word2 + " for " + (2020 - k) + " years. " + word2 + " is in " + word3 + ".");
System.out.println(" ");
} while (!"q".equals(sentence));
do {
System.out.println("Thanks for using the translator program.");
System.out.println(" ");
System.out.println("The program is now terminated");
} while ("q".equals(sentence));
First of all you should probably share you error message so community members can better understand your problem. But nonetheless your code should be while(!sentence.equals("q")), since you basically want to call the .equals() method, and you need to create a type String Object for that. "q" is just a String expression that can be passed into the .equals() method.
The part that I'm struggling with is ending the loop - getting "q" to terminate the program. Instead I get an error. Please let me know what I can do.
I have solved the part where you were struggling, but your program logic is incorrect and you need to work on that. For that learn about String class and its functions.
Anyway, here is your program press q to exit code
Scanner scan = new Scanner(System.in);
String sentence;
boolean doAgain = true;
do
{
System.out.println("Please enter the input sentence (press q to exit)");
sentence = scan.nextLine();
if("q".equals(sentence))
{
doAgain = false;
}
else
{
//your program logic in here
int i = sentence.indexOf(' ');
String word = sentence.substring(0, i);
String sentence2 = sentence.substring(i + 9, sentence.length());
int j = sentence2.indexOf(' ');
String word2 = sentence2.substring(0, j);
Matcher matcher = Pattern.compile("\\d+").matcher(sentence);
matcher.find();
int k = Integer.valueOf(matcher.group());
String sentence3 = sentence2.substring(j + 1, sentence2.length());
int l = sentence3.indexOf(' ');
String word3 = sentence3.substring(0, l);
System.out.println(word + " stays in " + word2 + " for " + (2020 - k) + " years. " + word2 + " is in " + word3 + ".");
System.out.println(" ");
}
} while (doAgain);
System.out.println("Thanks for using the translator program.");
System.out.println(" ");
System.out.println("The program is now terminated");

Java string inside string

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2

Where did I go wrong with this cipher program?

I need to write a program that takes the first, middle, and last name of a person and encrypt it: each letter the user enters is shifted circularly by the selected key. For example, if the key is 1 and the original letter is ‘A’, then the encrypted letter will be ‘B’. If the key is 3 and the original letter is ‘b’, then the encrypted letter will be ‘e’. If the key is 3 and the original letter is ‘z’, then the encrypted letter will be ‘c’.
Here is my code:
import java.util.Scanner;
public class Cipher {
public static void main(String []main){
Scanner console = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstname = console.nextLine();
System.out.print("Enter your middle name: ");
String middlename = console.nextLine();
System.out.print("Enter your last name: ");
String lastname = console.nextLine();
System.out.print("enter the key ");
int N = console.nextInt();
String s = firstname + middlename + lastname;
System.out.print("your original name is "+ s);
String empty = "";
for( int i = 0; i<=s.length();i++){
if (s.charAt(i)!=' '){
System.out.print(empty ="" + s.charAt(i));
}
else{
System.out.print(empty +=s.charAt(i+N));
}
}
System.out.print("encrypted name is " + empty);
}
}
My problem seems to be in the loop, but I have no idea how to fix it.
What I am getting:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abcaababcException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at test1.test.main(test.java:19)
While what I should be getting for example is the following:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abc
encrypted name is cde
Consider using this code instead of your last for-loop :
byte[] input = s.getBytes();
for (int i = 0; i < input.length; ++i) {
input[i]+= N;
}
String encrypted = new String(input);
System.out.print("encrypted name is " + encrypted);
Should be fine on ASCII symbol sets.
You cannot use this:
s.charAt(i+N)
Since it will access characters that are 'after' the string - you may use indices from 0 to s.length()

Java not showing last letter of string correctly?

So I have this little program and all it needs to do is check if the last letter of the last name is an "s". And if it is an "s" itll change the last name to plural.
Ex.
Smith = Smith's
Smiths = Smiths'
Changes the last name to plural. Simple right? Seems so, but my if statement isnt detecting if the last letter is an "s"
Here's some code
import javax.swing.JOptionPane;
public class Lastname {
public static void main(String[] args) {
String messageText = null;
String title = null;
int messageType = 0;
String lastName = "";
String pluralLastName = "";
Input input;
input = new Input();
messageText = "Please enter a last name. I'll make it plural.";
title = "Plural Last Names";
messageType = 3;
lastName = input.getString(messageText,title,messageType);
int intLength = lastName.length();
String lastLetter = lastName.substring(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter.equals('s'))
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'" );
else
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'s" );
}}
The if statement always just adds an "'s" to everything.
You need to use double quotes to represent a String literal.
if (lastLetter.equals("s"))
Otherwise you are comparing a String with a Character which will always return false.
Instead of comparing Strings, you can compare chars:
char lastLetter = lastName.charAt(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter == 's')
Right now, you are comparing Strings to chars.

Categories