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.
Related
I have a String that goes "Peyton Manning; 49". Is there a way to have the computer read the left side of the String and make it equal to a new String "Peyton Manning" and take the right side of the String and make it equal to an int with a value of 49?
A number of ways spring to mind: you can tokenize or you can use regexs. You didn't specify about white space padding. Also, you didn't specify if the string segments around the delimiter can be invalid integers, mixtures strings digits etc. If this helped you, please mark accordingly.
public class Test {
public static void main(String[] args) {
String s="Blah; 99";
StringTokenizer st = new StringTokenizer(s, ";");
String name = st.nextToken();
Integer number = Integer.parseInt(st.nextToken().trim());
System.out.println(name.trim() + "---" + number);
number = Integer.parseInt(s.replaceAll("[^0-9]", ""));
name = s.replaceAll("[^A-Za-z]", "");
System.out.println(name + "---" + number);
int split = s.indexOf(";");
name = s.substring(0, split);
number = Integer.parseInt(s.substring(split+2, s.length()));
System.out.println(name + "---" + number);
}
}
The simplest way is:
String text = input.replaceAll(" *\\d*", "");
int number = Integer.parseInt(input.replaceAll("\\D", ""));
See KISS principle.
Here is what I have:
Scanner input = new Scanner(System.in);
System.out.print("Enter an uppercase letter: ");
String Letter = input.next();
String LettersTwo = "A" + "B" + "C";
String DigitTwo = LettersTwo.substring(0) + "2";
String LettersThree = "D" + "E" + "F";
String DigitThree = LettersThree.substring(0) + "3";
String LettersFour = "G" + "H" + "I";
String DigitFour = LettersFour.substring(0) + "4";
String LettersFive = "J" + "K" + "L";
String DigitFive = LettersFive.substring(0) + "5";
String LettersSix = "M" + "N" + "O";
String DigitSix = LettersSix.substring(0) + "6";
String LettersSeven = "P" + "Q" + "R" + "S";
String DigitSeven = LettersSeven.substring(0) + "7";
String LettersEight = "T" + "U" + "V";
String DigitEight = LettersEight.substring(0) + "8";
String LettersNine = "W" + "X" + "Y" + "Z";
String DigitNine = LettersNine.substring(0) + "9";
if (Letter.contains(LettersTwo)) {
System.out.println("The corresponding digit is " + DigitTwo);
}
If the user inputs an uppercase letter of A, B, or C, I want the system to print out, "The corresponding number is 2". I correlated the number to the uppercase letter in substrings. The system isn't printing that out and what I have it as is if Letter contains something from LettersTwo, then to print that out. I am new to programming though so I don't know if I have that written correctly. Can someone help me get this working?
Take another look at your if statement:
if (Letter.contains(LettersTwo))
Here you're checking to see if a single letter contains a string of letters. Logically that'll return false. But if you use it this way:
if (LettersTwo.contains(Letter))
You're checking if a group of letters contains a single letter.
The most obvious approach is to use an if statement or switch statement. Anther approach, which seems to be what you are trying to do, is to use an array of String. (Note that when you start adding numbers to the end of a variable name, this is a strong indication that you should use an array.) If you want to get fancy, you can turn this into a lookup table with a Map<Character, Integer>.
You should also look at the documentation for String.contains(). It doesn't work the way you are trying to use it.
I am trying to write a static method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters).
The longest name should be printed with its first letter capitalized and all subsequent letters in lowercase, regardless of the capitalization the user used when typing in the name. If there is a tie for longest between two or more names, use the tied name that was typed earliest. Also print a message saying that there was a tie, as in the right log below.
In the event some of shorter names tie in length, such as DANE and Erik ; but don't print a message unless the tie is between the longest names.
public static void longestName(Scanner console, int n) {
String name = "";
String longest= "";
boolean areTies = false;
for(int i=1; i<=n; i++) {
System.out.print("Enter name #" + i + ":");
name = console.next();
if(name.length( ) > longest.length( )) {
longest = name;
areTies = false;
}
if(name.length( ) == longest.length( ) ) {
areTies = true;
}
}
// now change name to all lower case, then change the first letter
longest = longest.toLowerCase( );
longest = Character.toUpperCase (longest.charAt( 0 ) ) + longest.substring(1);
System.out.println(longest + "'s name is longest");
if(areTies==true) {
System.out.println(" (There was a tie! ) " );
}else{
System.out.println();
}
}
My output is :
Enter name #1:roy
Enter name #2:DANE
Enter name #3:Erik
Enter name #4:sTeFaNiE
Enter name #5:LaurA
Stefanie's name is longest
(There was a tie! )
It will just print there was a tie for every invokation.I have no idea why.
Secondly,
longest = longest.toLowerCase( );
longest = Character.toUpperCase (longest.charAt( 0 ) ) + longest.substring(1);
My friend taught me to use this to retrieve the word but i still dont understand.Is there other way of doing it?It is very complicated for me.
You have a problem with your logic. When you find a new longest name (first if statement), you set longest to be name. Then the second if executes. Because at this point longest refers to the same object as name, of course their lengths are equal. To avoid this, just insert an else.
else if(name.length( ) == longest.length( ) ) {
Let's break down how it's changed to first character uppercase, rest lowercase.
longest = longest.toLowerCase( );
Now longest is all lowercased.
Character.toUpperCase (longest.charAt( 0 ) )
This takes the first character and uppercases it.
longest.substring(1);
This takes the substring starting at index 1 (the second character) through the end of the string, which is concatenated with the uppercased character.
import java.util.*;
public class Longest {
public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
System.out.print("Enter the number of names you wanna enter? ");
int n = input.nextInt(); // takes number of names
longestName(input,n); // function call
}
public static void longestName(Scanner input, int n)
{
String name = ""; // First assign name to the empty string
String longest = ""; // First assign longest to the empty string
boolean areTies = false; // Assume there are no ties at first place
for(int i = 1; i <= n; i++) // run a loop n times
{
System.out.print("Enter name #"+i+":");
name = input.next(); // takes ith name
if(name.length() > longest.length()) /*if length of the entered new string is greater than current longest*/
{
longest = name;
areTies = false; // no tie
}
else if(name.length() == longest.length()) /*if both strings are of same length*/
areTies = true; // so boolean value of areTies is true
}
// now change the name to the lower case and then change only first letter to the upper case
longest = longest.toLowerCase(); // changes entire string to lowercase
longest = Character.toUpperCase(longest.charAt(0)) + longest.substring(1); /* first char to upper and rest remains as it is and concatenate char and remaining string from index 1 to rest*/
System.out.println(longest + "'s name is longest");
if(areTies==true) {
System.out.println(" (There was a tie! ) " );
}else{
System.out.println();
}
}
}
public static void longestName(Scanner console, int names) {
String longest = "";
boolean tie = false;
for ( int i = 1; i <= names; i++){
System.out.print("name #" + i + "? ");
String name = console.nextLine();
if (name.length() == longest.length()){
tie = true;
}
if (name.length() > longest.length()){
longest = name;
tie = false;
}
}
longest = longest.toLowerCase();
System.out.print(longest.substring(0,1).toUpperCase());
System.out.println(longest.substring(1) + "'s name is longest");
if (tie){
System.out.println("(There was a tie!)");
}
}
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);
I just started learning Java and I'm having trouble formatting string. In the problem I have a string a user inputted that is a name in the format: "First Middle Last". I need to output the string in the format: "Last, First MI. " (MI is middle initial).
Here is what I have so far, I have the first name working, but unsure how to go about getting the last and middle initial out of the string.
// Variable declarations
String name, first, last, middle;
Scanner scan = new Scanner (System.in);
// Get name from user in format "First Middle Last"
System.out.println("Enter the person's name: ");
name = scan.nextLine();
// Get first, middle initial, and last name from the string
first = name.substring(0, name.indexOf(" "));
middle =
last =
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middle + ".");
so for example if the user entered: "John Robert Doe", it would output as "Doe, John R."
Any help is appreciated.
You can use the split method of the String class
// Get first, middle initial, and last name from the string
String nameParts [] = name.split(" ");
// not sure if you need these variables, but I guess you get the picture
first = nameParts [0];
middle = nameParts [1];
last = nameParts [2];
middleInital = middle.charAt(0);
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middleInital + ".");
Take a look at the String.split method. This allows you to find the substrings. Then you only have to place them in the correct order
Take a look at String split and charAt method of String class.
String person_data = "John Robert Doe" ;
String[] data = person_data.split(" ");
char MI = data[1].charAt(0);
System.out.println(data[2] +","+ data[0] + " "+ MI);
Output = Doe,John R
Here
Data[0] == "John"
Data[1] == "Robert"
Data[2] == "Doe"
MI = first character of Data[1] which is R.
Try this:
String name = "First Middle Last";
String[] data = name.split(" ");
String formatted = String.format("%s, %s %c.", data[2], data[0], data[1].charAt(0));
The last line assigns the value "Last, First M." to the variable formatted, as expected. This solution makes use of Java's Formatter class, which is a big help for all your string formatting needs.
You will need to first split the string (using String.split) and then format it.
Forgive me since I'm typing this on my iPad, the answer will look as follows:
String names = name.split("\\s+"); \\Split on whitespaces, including tab, newline and carriage return.
StringBuilder sb = new StringBuilder();
for (int x = 0; x < names.length; x++) {
switch (x) {
case 0: sb.apppend(names[names.length - 1]).append(", ");
break;
case 1: sb.append(names[0]).append(" ");
break;
case 2: sb.append(Character.toUpperCase(names[1].charAt(0))).append(".");
break;
default: break;
}
}
String fullName = sb.toString();