I'm trying to write code in Java that will output abbreviated names based on input. For example; if the input is "John Alex Smith", the output is "Smith, J.A." And if the input is "John Smith", the output is "Smith, J." my code works perfectly fine if a first, middle, and last name are input, but it doesn't work if only a first and last are input, and I can't figure out why?
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName = scnr.next();
String middleName = scnr.next();
String lastName = scnr.next();
char middleInitial = middleName.charAt(0);
char firstInitial = firstName.charAt(0);
if (middleName.length() > 0 && lastName.length() == 0) {
lastName = middleName;
System.out.println(lastName + ", " + firstInitial + "."); }
else if (lastName.length() > 0) {
System.out.println(lastName + ", " + firstInitial + "." + middleInitial + "."); }
/* Type your code here. */
}
}
I assume your inputting 2 strings and then just pressing return for the case of a first and last name only? In which case firstName will have the first String. middleName will have the second String and then lastName will be an empty String . There are no conditions in your if else that support that siutation so nothing is printed.
You'll want to change it to check:
If firstName or middleName is null or empty then that's an error
Otherwise is last name not null and not empty? If so then that's 3 named input
Otherwise it's 2 named input
Related
I don't really know how to explain the problem. I do have a scanner imported after the package. I'm not sure if you can stack methods, and if you can I'm definitely doing it wrong.
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.next();
name.trim();
name.toUpperCase(name.substring(name.charAt(name.indexOf(" "))));
System.out.println("Your name is: " + name);
Just split the String into the first word and second word based on the indexOf(" ")
Capitalize the second word using toUpperCase
Concatenate both words together using +
name = name.substring(0, name.indexOf(" ")) + name.substring(name.indexOf(" ")).toUpperCase();
Note: Not sure if you are required to handle invalid input, but this code would only work assuming a valid two-word name is entered, with a space in-between
Also, make sure to change console.next() to console.nextLine() to ensure you retrieve the entire line of input
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.nextLine();
String[] words = name.split(" ");
words[1] = capitalizeWord(words[1]);
name = String.join(" ", words);
System.out.println("Your name is: " + name);
}
private static String capitalizeWord(String s) {
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
return s;
}
At first you split the input into a String array. Then you replace the first character of the 2nd (index 1) element and join the array back to a String.
Input: john doe, Output: john Doe
String is immutable in java so if you want to "change" a Strig variable value, you need to reassign it to itself. I think a good approach to prepare more than 2 input, many people has middle name e.g.
This function split the input into parts then make the first letter uppercase then return the whole name after concat them with space.
public String capitalizeName(String name) {
String[] nameParts = name.split(" ");
for (int i = 0; i < nameParts.length; i++) {
nameParts[i] = nameParts[i].substring(0, 1).toUpperCase() + nameParts[i].substring(1);
}
return String.join(" ", nameParts);
}
String is immutable in Java.
BE SIMPLE!!!
public static void main(String... args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your first name and last name: ");
String firstName = upperCaseFirstLetter(scan.next().trim());
String lastName = upperCaseFirstLetter(scan.next().trim());
System.out.println("Your name first name: " + firstName);
System.out.println("Your name last name: " + lastName);
}
private static String upperCaseFirstLetter(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
One solution would be to make the String a String array using the split(regex)-method. It will split up a string into a String array, breaking them up at regex.
For example:
String text = "This is a text.";
String textArray = text.split(" ");
for(String element : textArray)
{
System.out.println(element);
}
will print
This
is
a
text.
If you got a String[] like that, you can choose the second String (index 1 of array) and capitalize it. You can do so in a foreach loop, for example.
String text = "This is a text.";
text = text.trim(); // if you want to trim it.
String[] textArray = text.split(" ");
String newText = "";
int index = 0;
for(String element : textArray)
{
if(index == 1)
{
element = element.toUpperCase();
}
newText = newText + element + " ";
index++;
}
System.out.println(newText);
If you want to handle errors, you can put in in a try-catch-block like this.
try
{
[Your code]
}
catch (Exception e)
{
System.out.println("An error occured.");
}
This is, of course, not a very short way to do it. However, it's easy to understand and it can handle even a string consisting of several words.
I am very new to Java. I'm in my first Java class and we are just working on the basics. I am supposed to write a program that prompts the user to enter their first, middle, and last name with spaces. Then display the length of the first name, the length of the middle name, the initials, and the full name in all upper case. Here is the class example
Example Output:
Enter a first name middle name and surname
Peggy Sue Palmer
Length of your name: 16 characters
Length of your middle name: 3 characters
Your initials are PSP
PEGGY SUE PALMER
I have worked on some code so far and I am able to get some of the output correctly but when I go to enter Peggy Sue Palmer I have to input the name one at a time with a space at the end and then press enter to input the next name. Also it displays the length of the middle initial as 4 instead of 3. I know that I can have the input all on one line by just having one input String name = input.nextLine(), which allows the input format I am looking for but if I do that I have no clue how to get the length of the middle name or the initials. Sorry this is a dumb question but this is my first Java class and we are just learning the basics.
package tracy2prog1;
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
System.out.println(firstname.length() + middlename.length() + lastname.length());
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + middlename.toUpperCase() + lastname.toUpperCase());
}
}
Here is the updated code that works, only issue is its not counting the spaces in the output of the full name to 16, I am getting 14.
package tracy2prog2;
import java.util.Scanner;
public class Tracy2prog2 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.next();
String middlename = input.next();
String lastname = input.next();
System.out.print("Your name is ");
System.out.println(firstname.length() + middlename.length() + lastname.length() + " characters");
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + " " + middlename.toUpperCase() + " " + lastname.toUpperCase());
}
}
I have to input the name one at a time with a space at the end and then press enter to input the next name.
Let's look at how you get the name:
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
You are reading three separate lines here which is why you have to press enter between each part of the name. Instead you should read the entire name at once:
String name = input.nextLine();
Now you need to parse the name into separate pieces. I'll leave this for you to figure out how to do. You should look at the documentation of the String class to find any functions which might be helpful to finish solving the problem.
Take a look at how you can do it (one of many examples) - Maybe this will help you in the future, as you probably don't know arrays yet (I didn't know you were in your first class, I went to the problem before reading all - don't do that by the way, sorry!)
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
//Here you will have your names without " ", then its length is 2 characters shorter
String[] names = input.nextLine().split(" ");
//As your names are in an array now, you can get then directly
System.out.println(names[0].length() + names[1].length() + names[2].length());
System.out.println("The length of your middle name is " + names[1].length() + " characters");
System.out.println("Your initials are " + names[0].charAt(0) + names[1].charAt(0) +names[2].charAt(0));
System.out.println(names[0].toUpperCase() + " " + names[1].toUpperCase() + " " + names[2].toUpperCase());
//Peggy Sue Palmer
//Considering you did this: String[] names = input.nextLine().split(" ");
//your array is ["Peggy", "Sue", "Palmer"]
//then array[0] is "Peggy"
//then "Peggy".length == 5
//plus: names[0].charAt(0) means "Peggy".charAt(0) which is "P"
System.out.println("The length of your first name is " + names[0].length() + " characters");
System.out.println("The initial of your first name is " + names[0].charAt(0));
}
}
I wrote a little program that prompts a user to enter their first middle and last name I then attempt to locate each white space and store the name that comes after the whitespace into a new String variable.
Problem: I want to locate the white spaces before each part of the name so that I can take each relative name and store it in a new String variable but i'm not sure where I'm going wrong.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name = "",
firstName = "",
middleName = "",
lastName = "";
boolean isName = false;
while(!isName)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
if(name.length() < 0)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
System.out.print("Invalid input");
}
else isName = true;
}
for(int j = 0; j < name.length(); j++)
{
if(name.charAt(j) == ' ')
{
firstName = name.substring(0, j); // Start at 0 end at first white space
middleName = name.substring(j + 1, name.length());
lastName = name.substring(j + 1, name.length());
}
}
System.out.println("\nLast Name, First Name, Middle Name: " + lastName + firstName + middleName );
}
}
The output I'm getting looks like this
Enter your name as 'First Middle Last': Adam Thomas Smith
Last Name, First Name, Middle Name: SmithAdam ThomasSmith
Any suggestions as to how to fix this?
name = name.trim(); // To avoid suprises, as Pshemo suggested.
String[] splitName = name.split("\\s+");
System.out.println("\nLast Name, First Name, Middle Name: "
+ splitName[2] + " " + splitName[0] + " " + splitName[1]);
Try this instead. It uses String.split() to split the name on a space (\\s+, a regex) and returns the values as an array. The names could also be assigned to a variable if you choose.
You can try the following code, just by splitting the 'name' variable on each space into an String[] Then by getting each value from the array and assigning to the value you wish.
String[] str = name.split(" ");
firstName = str[0];
middleName = str[1];
lastName = str[2];
Better to use split(" ") function... It will change you string to an string array. Eg:-
String names = "Madan mohan malviya";
String arr[] = name.split(" ");
for( name :names){
System.out.println(name); // print each string content
}
public class Registration {
public static void main(String[] args) {
final String MY_DELIMITER = "','";
boolean tryAgain = true;
String fName = "";
String A = fName.substring(0,2);
String lName = "";
int lNameLength = lName.length();
String B = lName.substring(lNameLength-4,lNameLength);
String address = "";
String zip = "";
String C = zip.substring(0,5);
String age = "";
String D = age.substring(0,1);
String gender = "";
String race = "";
String regList = "";
Scanner myScanner = new Scanner(System.in);
boolean showList = false;
// Get input from the user until they type "q"
// For each input check for "q"
// if not q, append the input
// to the existing String + the delimiter
while(tryAgain)
{
System.out.println("Name: (q to quit)");
fName = myScanner.nextLine();
System.out.println("Last Name: (q to quit)");
lName = myScanner.nextLine();
System.out.println("Addess: ");
address = myScanner.nextLine();
System.out.println("Age: ");
age = myScanner.nextLine();
System.out.println("Gender: ");
gender = myScanner.nextLine();
System.out.println("Race: ");
race = myScanner.nextLine();
if(fName.equals("q"))
{
tryAgain = false;
}
else
{
// Append new name to the list using a delimiter
regList = fName + lName + "\n" + address + "\n" + age + "\n" + gender + "\n" + race + MY_DELIMITER;
}
} // end of while( )
System.out.println("Here is your registration:" + regList);
// Convert the String into an array, using the same delimiter
String[ ] regArray = regList.split(MY_DELIMITER);
// Ask the user if they want to display the contents of the array
// If "y" then display the list using a foreach loop
System.out.println("Would you like to see the registration from the Array? [y-n]");
fName = myScanner.nextLine( );
myScanner.close();
fName = fName.toLowerCase( );
showList = fName.equals("y")?true:false;
if(showList)
{
// Display the results using for each
System.out.println("Here is your registration from the array: ");
// Use a for each statement instead of the more complex for( ) loop
// for(int counter=0; counter < employeeArray.length; counter++)
for(String thisReg:regArray)
{
System.out.println(thisReg);
System.out.printf("USER ID: ", A + "-" + B + "-" + C + "-" + D);
}
} // end of if(showList)
}
}
I am trying to extract out the first 3 letters of the fName input, so I figured I could use fName.substring to do that, but it gives me this error.
Sorry I didn't add all of my code, to save time. Apparently it looked confusing. Any way so the fName input is the name of the user. Can it not be in that order?
Erm...your sequence of operations is suspect. Everywhere, actually.
Look at the following interaction:
String fName = "";
String A = fName.substring(0,2);
You declare an empty string, then immediately take the substring of it. Where are you getting the data for the substring from? There's nothing to substring here - the empty string has a length of zero.
You should be certain that you're putting data into your string before taking a substring of it. Using a Scanner would go a long way here.
Or better yet, moving your instance of myScanner at the top of main would make it much clearer as to where that's supposed to go, and how it's supposed to work.
Always check the length of string before substring anything. Especially when a user is giving you this variable.
You are trying to get a substring of an empty string.
String fName = "";
String A = fName.substring(0,2); // here fName is empty!!!
Change fName into some actual String and also check for length of the String before calling substring to make sure substring of the size you want exists.
String fName = "somestring";
if(fName.length() >= 2) {
String A = fName.substring(0,2);
System.out.println(A); // prints out "so"
}
That is the case with all of your other Strings as well.
I have a user input their name as a string and then the name is printed out onto the screen. How can i limit what is printed to only 12 characters so that a user cannot type an insanely long name? Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your player name: ");
String name= input.next();
System.out.print("\n" + name + " has started the game\n");
Something like:
String name = input.next();
name = name.length() > 12 ? name.substring(0, 11) : name;
and accept some of your previous answers.
{
public static void main (String[]args){
String s = new String();
String n = new String();
s = "ya ali madad";
if (s.length() > 10) {
n = s.substring(10, 12);
}
System.out.println("String s:" + s);
System.out.println("String n:" + n);}}