I've been learning Java and for some reason, I'm having a brain fart on how to add two strings together. In the program, I successfully have the program state what the length of the First and Last names are independently. However I would like to have the program also state how many characters there are in the name.
I know that I need to assign the string lengths to an integer variable that can be added together, but I'm just blanking at the moment.
My source code is as follows, thank you for your help!
import java.util.Scanner;
/*
* //Program Name: stringwk7
* //Author's Name: MrShiftyEyes
* //Date: 05-12-2013
* //Description: Prompt for a user name; print initials;
* // print out the reverse name, find the length of the names
*/
/**
*
* #author MrShiftyEyes
*/
public class stringwk7{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Create first name and last name StringBuffers
Scanner input = new Scanner(System.in);
System.out.print("What is your first name? ");
StringBuffer firstName = new StringBuffer(input.nextLine());
System.out.print("What is your last name? ");
StringBuffer lastName = new StringBuffer(input.nextLine());
// Declare two string variables using StringBuffer variables
String fName = new String(firstName);
String lName = new String(lastName);
// Display the users initials
System.out.println("Your initials are: " + firstName.charAt(0) + " " + lastName.charAt(0));
// Displays the user's name in reverse
System.out.println("Your name in reverse is: " + lastName.reverse() + " " + firstName.reverse());
// Length of name
System.out.println("The length of my first name is " + firstName.length());
System.out.println("The length of my last name is " + lastName.length());
// Insert a goodbye into the firstName string and display to user
firstName = firstName.reverse(); // Change firstName back to the initial value
System.out.println(firstName.insert(0, "See ya later, "));
}
}
you just mean the first and last name together?
int fullNameLength = lastName.length() + firstName.length();
System.out.println("The length of my full name is " + fullNameLength);
(firstName + lastName).length()
Related
example of output should be
please help thank you in advance!!
the output of the code in username should be the 2 letter in firt name and 3 in last name and date number
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter Fullname:");
String fullname = sc.nextLine();
System.out.println("Enter Birthday : ");
String bday = sc.nextLine();
System.out.println("Your Login Details");
System.out.println("Enter Fullname:" + fullname);
System.out.println("Enter Birthday : " + bday);
System.out.println("Enter Username: " + );
}
}
Assuming the input will always be in the format you provided, you can use String.split() and String.substring() to extract the required information from the input as shown below.
String[] splitName = fullName.split(" ");
String firstName = splitName[0];
String lastName = splitName[1];
String day = bday.split("-")[1];
String username = firstName.substring(0, 2) + lastName.substring(0, 3) + day;
You can use this code to achieve the expected result. The name should always be in this format FirstName LastName, otherwise, you may encounter NullPointerException more frequently. There are split and substring methods in the string class. Follow these steps to get started
Full name should be split into two strings, the first is for the first name and another is for the last name, for this we will use the split method which returns String[].
After splitting the full name, the substring method comes into the picture, substring method takes two parameters first and the last index. We can use this method with both strings received by the split method.
String[] firstLastName = fullname.split(" ");
System.out.println("Enter Username: " + firstLastName[0].substring(0, 2) + firstLastName[1].substring(0, 3) + bday.split("-")[1]);
Syntax
Public String [] split ( String regex, int limit)
public String substring(int begIndex, int endIndex)
I'm working on a .xml file generator. It works by asking the user to input 5 different values and then using them for generating a .xml data container. This is the code:
public class Generator {
public static void main(String[] args) throws InterruptedException {
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("Input the furni ID (input only numbers here).");
String furniID = reader.nextLine();
System.out.println("Input the furni's file name (without '.swf'. You can input numbers, letters and underscores here).");
String furniFileName = reader.nextLine();
System.out.println("Input the furni's revision (input only numbers here).");
String furniRevision = reader.nextLine();
System.out.println("Input the furni's name (this will be the name that it will display when you click on the furni in a room or in your inventory).");
String furniName = reader.nextLine();
System.out.println("Input the furni's description (this will be displayed under the furni's name).");
String furniDescription = reader.nextLine();
System.out.println("Input the furni's furniline. This is just a name for a group of furnis that belong to the same collection. For example you can input 'custom' (without quotation marks).");
String furniLine = reader.nextLine();
System.out.println("Generating your furnidata...");
System.out.println(" ");
TimeUnit.SECONDS.sleep(1);
System.out.println("<furnitype id=\"" + furniID + "\"" + " classname=\"" + furniFileName + "\"" + ">");
System.out.println("<revision>" + furniRevision + "</revision>");
System.out.println("<xdim>1</xdim>");
System.out.println("<ydim>1</ydim>");
System.out.println("</partcolors>");
System.out.println("<name>" + furniName + "</name>");
System.out.println("<description>" + furniDescription + "</description>");
System.out.println("</adurl");
System.out.println("<offerid>-1</offerid>");
System.out.println("<buyout>0</buyout>");
System.out.println("<rentofferid>-1</rentofferid>");
System.out.println("<rentbuyout>0</rentbuyout>");
System.out.println("<bc>0</bc>");
System.out.println("<excludeddynamic>0</excludeddynamic>");
System.out.println("<customparams/>");
System.out.println("<specialtype>1</specialtype>");
System.out.println("<canstandon>0</canstandon>");
System.out.println("<cansiton>0</cansiton>");
System.out.println("<canlayon>0</canlayon>");
System.out.println("<furniline>" + furniLine + "</furniline>");
System.out.println("</furnitype>");
System.out.println(" ");
System.out.println("Do you want to generate another furnidata? (YES/NO)");
String confirmation = reader.nextLine();
if (confirmation.equals("NO")) {
System.out.println("Furnidata generator has been stopped.");
break;
} else if (confirmation.equals("no")) {
System.out.println("Furnidata generator has been stopped.");
break;
} else if (confirmation.equals("No")) {
System.out.println("Furnidata generator has been stopped.");
break;
}
}
}
I want the program to detect when someone inputs an empty string by pressing the enter key with no written text and print a message asking the user to not input empty strings. I tried this with a try-catch statement but after printing the message the program executes the next line instead of re-executing the one where the user input an empty string. How can I achieve this?
Whenever you have a prompt for a User to supply specific data you should validate that data that was entered and if it is incorrect, permit the User to try again so as not to halt the application due to an error of some kind that can be avoided. There is no problem using Regular Expressions (regex) for this sort of thing.
A User entering nothing (by just hitting the ENTER key) is just one problem. At some prompts you are expecting the User to enter only numerical digits. A small regex within the String#matches() method is ideal for this, for example:
if (!userInput.matches("\\d+") {
System.out.println("Invalid input! Numerical digits only!");
}
If the User input does not match all numerical digits then display "Invalid Input!".
Every prompt should be in its own do or while loop so that validation can be done and an opportunity for the User to re-enter the data can be accomplished. If you have lots of prompts then a class method can be created to handle all of them in order to remove duplicate coding. As an example, here is your code modified so that a method named askUser() can handle the prompts to the User:
public class Generator {
public static void main(String[] args) {
java.util.Scanner reader = new java.util.Scanner(System.in);
while (true) {
// Only a String repesentation of numerical digits will be accepted.
// 1 to 20 digits are acceptable)
String furniID = askUser(reader, "Input the furni ID (input only numbers here).",
"\\d{1,20}");
/* Only characters A to Z in either upper or lower case, digits
from 0 to 9, whitespaces, and underscores will be accepted
within the Users input. The period (.) is not acceptable
therefore eliminating the possibility of a file name extension
like .swf to be applied to the supplied file name. File name can
be 1 to 80 characters. */
String furniFileName = askUser(reader, "Input the furni's file name (without "
+ "'.swf'.\nYou can input numbers, letters and underscores here).",
"(?i)[a-z0-9 _]{1,80}");
// Only a String repesentation of numerical digits will be accepted.
// 1 to 20 digits are acceptable)
String furniRevision = askUser(reader, "Input the furni's revision (input "
+ "only numbers here).", "\\d{1,20}");
/* Only characters A to Z in either upper or lower case, digits
from 0 to 9, whitespaces, and underscores will be accepted
within the Users input. The period (.) is not acceptable. The
name can be 1 to 25 characters in length. */
String furniName = askUser(reader, "Input the furni's name (this will be "
+ "the name that will\nbe displayed when you click on the furni in "
+ "a room or in\nyour inventory).", "(?i)[a-z0-9 _]{1,25}");
/* Only characters A to Z in either upper or lower case, digits
from 0 to 9, whitespaces, and periods will be accepted within
the Users input. Description can be a minimum of 5 to a maximum
of 120 characters in length. */
String furniDescription = askUser(reader, "Input the furni's description ("
+ "this will be displayed\nunder the furni's name).", "(?i)[a-z0-9. ]{5,120}");
/* Only characters A to Z in either upper or lower case, digits
from 0 to 9, and whitespaces will be accepted within the Users
input. The period (.) is not acceptable. The furniline name can
be 1 to 25 characters in length. */
String furniLine = askUser(reader, "Input the furni's furniline. This is just "
+ "a name for a\ngroup of furnis that belong to the same collection. "
+ "For\nexample you can input 'custom' (without quotation marks).",
"(?i)[a-z0-9 ]{1,25}");
System.out.println("Generating your furnidata...");
System.out.println(" ");
System.out.println("<furnitype id=\"" + furniID + "\"" + " classname=\"" + furniFileName + "\"" + ">");
System.out.println("<revision>" + furniRevision + "</revision>");
System.out.println("<xdim>1</xdim>");
System.out.println("<ydim>1</ydim>");
System.out.println("</partcolors>");
System.out.println("<name>" + furniName + "</name>");
System.out.println("<description>" + furniDescription + "</description>");
System.out.println("</adurl");
System.out.println("<offerid>-1</offerid>");
System.out.println("<buyout>0</buyout>");
System.out.println("<rentofferid>-1</rentofferid>");
System.out.println("<rentbuyout>0</rentbuyout>");
System.out.println("<bc>0</bc>");
System.out.println("<excludeddynamic>0</excludeddynamic>");
System.out.println("<customparams/>");
System.out.println("<specialtype>1</specialtype>");
System.out.println("<canstandon>0</canstandon>");
System.out.println("<cansiton>0</cansiton>");
System.out.println("<canlayon>0</canlayon>");
System.out.println("<furniline>" + furniLine + "</furniline>");
System.out.println("</furnitype>");
System.out.println(" ");
// Only y or n can be supplied in any letter case.
// Anything else generates an Invalid Input message.
String confirmation = askUser(reader, "Do you want to generate another furnidata? (y/n)",
"(?i)[yn]", "Invalid Choice! Either 'y' for Yes or 'n' for No!");
if (confirmation.equalsIgnoreCase("n")) {
System.out.println("Furnidata generator has been stopped.");
break;
}
}
}
/**
* Displays the supplied prompt within the Console Window and permits the User
* to enter a response. User input is validated based on the regex argument
* supplied to the <b>validationRegEx</b> parameter.<br><br>
*
* #param inputReader (Scanner) Scanner object to use for User Input.<br>
*
* #param promptString (String) The prompt to display within the console window.<br>
*
* #param validationRegEx (String) A regular expression that will be used
* within a <b>String#matches()</b> method to validate the User's input.<br>
*
* #param errorString (Optional - String) Default validation error message is:<pre>
*
* "Invalid input! Try again..."</pre><br>
*
* Here you can optionally supply your own message for non-valid entries.<br>
*
* #return (String) The valid response from User.
*/
public static String askUser(java.util.Scanner inputReader, String promptString, String validationRegEx, String... errorString) {
String userInput = "";
String errString = "Invalid input! Try again...";
if (errorString.length > 0 && !errorString[0].trim().isEmpty()) {
errString = errorString[0];
}
while (userInput.isEmpty()) {
System.out.println();
System.out.println(promptString);
userInput = inputReader.nextLine();
if (!userInput.matches(validationRegEx)) {
System.err.println(errString);
userInput = "";
}
}
return userInput;
}
}
You might want to use.
String furniID = reader.nextLine();
furniID = furniID.trim();
if(furniID.equals("")){
System.out.println("Empty Here. ");
}
As suggested in comments .readLine() returns an empty string if you supply a blankline or simply hit enter.
The above regex expression will take care of empty string "" or whitespaces that user might enter.
edit 1
As suggested in comments regex could have been over-kill here. The string.trim() will take care of tabs, trailing-leading whitespaces and empty string.
This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}
I'm trying to read separate names and instruments up until the total number of bandmembers(asked earlier in the program) is reached. The program reads the amount, and reads the first name. However after that it fails in that it only reads the first name, it does not print any name or instrument after.
The while loop below is the most likely source of the problem:
i = counter
while(i <= bandMembers)
{
System.out.println("What is band member " + i + "'s name?");
kb.nextLine();
String bName = kb.nextLine();
System.out.println("What instrument does " + bName + " play?");
kb.nextLine();
String bNamePlay = kb1.nextLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
This is what it prints if I entered the first name as bName1:
Band Members
--------------
1: bName1 -
2: -
3: -
Any help appreciated, thanks.
Use BufferedReader instead.This will fix your problem.:-
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=counter;
while(i<=bandMembers){
System.out.println("Enter band member "+i+" name:-");
String bName=br.readLine();
System.out.println("What instrument does "+bName+" play?");
String bNamePlay=br.readLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
You should be using
String bName = kb.next();
Under the assumption that you are using a Scanner.
When you call nextLine() it reads the remainder of the same line and does not wait for input.
I don't have enough rep to comment on the issue you're having:
I was using kb.next at first but it read each word separated by a space as the next name. For example I would input "Jimmy loose hands" and it would prompt for Jimmy's instrument correctly, but it would then ask for band member 2's name and "what instrument does loose play?" simultaneously. So it took the second word as the next name.
What you may want to do is remove the "kb.nextLine();" before "String bName = kb.nextLine();"
I don't have an IDE open to confirm it, but that may be the reason that it is taking the second word/string entered as the name.
Right now I am making a small program which should create an email adress and username out of the users actual name. For example, Peter Anderson types his first and last name in two separate text fields, and the program should then return a username and an email adress in two separate textfields, once you press the save button. For example, Peter Anderson gets the username "a13petand" and the email adress "a13petand#test.com" a = autumn, 13 = 2013. It should only take the first 3 letters from first & last name. It should then append the first name, last name, username and email adress to the text area. This is how my code currently looks like;
package test5;
import javax.swing.JOptionPane;
public class Test5 extends javax.swing.JFrame {
String[][] Users = new String[20][4];
int counter;
public Test5() {
initComponents();
}
private void savebtnActionPerformed(java.awt.event.ActionEvent evt) {
if (counter < Users.length) {
Users[counter][0] = Firstnametf.getText();
Users[counter][1] = Lastnametf.getText();
Users[counter][2] = Usernametf.getText();
Users[counter][3] = Emailtf.getText();
jTextArea1.append(Users[counter][0] + ", " + Users[counter][1] + ", " + Users[counter][2] + ", " + Users[counter][3] + "\n");
counter++;
} else {
JOptionPane.showMessageDialog(null, "The array is full!");
counter = Users.length;
}
}
How should I continue from here? How do I make it generate "a13" and then take the first 3 letters in the first and last name? That is my main problem. All I know is that I should use the String class method substring to pick the first 3 letters out of first & last name. And then use the Calendar class to get the correct year. But I don't know how to make it work with my current code, which is the problem.
Date date = Calendar.getInstance().getTime();
String result = "";
result += new SimpleDateFormat("MMM").format(date).substring(0,1).toLowerCase();
result += new SimpleDateFormat("yy").format(date);
result += Firstnametf.getText().subString(0,3);
result += Lastnametf.getText().subString(0,3);
you should use
firstName = Firstnametf.getText().subString(0,3);
lastName = Lastnametf.getText().subString(0,3);
currentYear = Calendar.getInstance().get(Calendar.YEAR);
voila = firstName.concat(lastName).concat(currentYear);
or
voila = firstName + lastName + currentYear.toString ;