I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials.
Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname
Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself.
import java.util.*;
public class Initials
{
public static void main (String[] args)
{
//create Scanner to read in data
Scanner myKeyboard = new Scanner(System.in);
//prompt user for input – use print to leave cursor on line
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String initials1 = name.substring(0, 1);
int initials2 = name.
//output Initials
System.out.println ("Initials Are " + initials1 + initials2 + initials3);
}
}
Users will enter a string like
"first middle last"
so therefore you need to get each word from the string.
Loot at split.
After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name.
First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet.
Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array.
StringBuilder builder = new StringBuilder(3);
for(int i = 0; i < splitStringArray.length; i++)
{
builder.append(splitStringArray[i].substring(0,1));
}
System.out.println("Initials Are " + builder.toString());
Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method.
Scanner myKeyboard = new Scanner(System.in);
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String[] nameParts = name.split(" ");
char firstInitial = nameParts[0].charAt(0);
char middleInitial = nameParts[1].charAt(0);
char lastInitial = nameParts[2].charAt(0);
System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial);
Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.
Related
import java.util.Scanner;
public class Project3 {
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
System.out.println("Welcome to mini mad libs!"); // word1-word3 are inputs that point out which words from the story need to be replaced.
System.out.printf("Please enter the story: ");
String story = keys.nextLine();
System.out.printf("Please enter the first word type that should be replaced:");
String word1 = keys.nextLine();
System.out.printf("Please enter the second word type that should be replaced:");
String word2 = keys.nextLine();
System.out.printf("Please enter the third word type that should be replaced:");
String word3 = keys.nextLine();
System.out.println();
System.out.println("Ok, the game is ready to play!"); //the replace strings are the new words that are replacing the original words in the story.
System.out.println("Please enter a word type to replace "+word1);
String replace1 = keys.nextLine();
System.out.println("Please enter a word type to replace "+word2);
String replace2 = keys.nextLine();
System.out.println("Please enter a word to replace "+word3);
String replace3 = keys.nextLine();
String storyV2 = story.toLowerCase();
String word1V2 = word1.toLowerCase();
String word2V2 = word2.toLowerCase();
String word3V2 = word3.toLowerCase();
storyV2=storyV2.replaceAll("[.,!]", " ");
int positionOf1= storyV2.indexOf(" "+word1V2+" ");
int positionOf2= storyV2.indexOf(" "+word2V2+" ");
int positionOf3= storyV2.indexOf(" "+word3V2+" ");
int length1 = word1.length();
int length2 = word2.length();
int length3 = word3.length();
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
String lib = story.replaceFirst(WordMod1, replace1); //lib serves as a string that has a version of the original story replaced by the three words one by one in the next lines below.
lib = lib.replaceFirst(WordMod2, replace2);
lib = lib.replaceFirst(WordMod3, replace3);
System.out.println();
System.out.println("Here is your little mad lib: \n"+ lib);
}
}
Mad libz is a game that replaces selected words from a sentence with other words of your choice. I cannot use if/else statements, loops or anything that is not string methods. My problem seems to be in this part of the code. I'm not too experienced with Java so it might look terrible.
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
This part is making a substrings that obtain the word in a sentence, for example if I want the word "noun", it looks the standalone word anywhere in the sentence instead of possible getting the word from other words like "pronoun" or "pronounced". PositionOf1 looks for the position between blank spaces and lenghtOf1 is the length of the original word we want to replace.
That is why this is also supposed to be case insensitive so that is why I made string storyV2, its a copy of the original set to lower case.
If you just want to replace one string with another, then why not using the replaceAll() method?
String story = "...";
String fromWord = "foo";
String toWord = "bar";
String newStory = story.replaceAll(" " + foo + " ", " " + bar + " ");
You could use more elaborate regex patterns for finding foo not only enclosed by spaces but all kinds of non-word characters, so you wouldn't need to remove characters like .,; etc. first as you currently do.
I want to be able to distinguish the user's input using spaces, where each string they input in one line is used for something different.
Specifically, each word they input is used in a method where I add an item to a list. The user will type 'add' followed by the item's type and age.
I have just messed around trying to figure something out but I am just lost.
if (input.equals("add")) {
scan.next(); ??
}
After the user types 'add', they then input a type and age for a vehicle that they want to add to a list. For example, 'car 7' may be typed so a new item in a list can be made, and 'car' will be its type and '7' will be its age.
To note: age is an int.
If the user enters:
car 7
all you need to do to read that line is:
String words[] = scan.nextLine().split(" ");
Now you have an array that contains the words of that line. For eg: words[0] would contain car, words[1] would contain 7, etc.
You can also read them one at a time as well as change the delimiter. Here are several examples.
String text = "The quick brown fox jumped over the lazy dog";
Scanner scan = new Scanner(text);
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();
And this one changes the delimiter between words. You can specify a regular expression pattern or a simple String.
text = "The:quick,+-brown::::fox:.:jumped++over,,,,the,+,+lazy---dog";
scan = new Scanner(text);
// regular expression delimiter. Any combo of one or more of the chars.
scan.useDelimiter("[:,.;+-]+");
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();
I'm trying to create a videoStore with the basic CRUD operation. For creating each movie I need to read the title, the year and the gender as below:
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
When I enter the addMovie option, I get this print on the console
(name: year:)
Can someone explain to me why it happens as above?
Here is the rest of the method:
static ArrayList<Movie> movies = new ArrayList<Movie>();
static Scanner in = new Scanner(System.in);
public static void InserirFilme() {
String name;
int year;
String gender;
boolean existe = false;
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
Movie movie = new Movie(name, year, gender);
for(Movie m: movies)
{
if(movie == m)
{
existe = true;
}
}
if(!existe)
{
movies.add(movie);
}
else
{
System.out.println("the movie already exists in the videoStore");
}
}
Calling next does not remove the line break, which means the next time you call InserirFilme the call to read the name can complete immediately. Use nextLine.
System.out.print("gender: ");
gender = in.nextLine();
(You probably mean "genre" instead of "gender" though)
Also, as mentioned in the comments, this check will never succeed:
if(movie == f)
You run this method in loop (right?)
The first call reads input correctly, but it leaves the linebreak in System.in after the last in.next().
On next call the name: is printed, then scanner reads an empty string from System.in because the linebreak already exists here.
And after thet the year: is printed on the same line because no new linebreaks are entered.
So you just have to insert another in.nextLine() after reading gender (or genre :) )
Or use nextLine() for read genre instead of next(), because genre might have more than one word.
But there are some disadvantages with using fake nextLine() to 'eat' linebreak - there might be another text which you doesn't process. It's a bad practice - to loose the data user entered.
It is better to read all the data from line, then validate/parse it, check isn't there some extra data, and if the data is invalid show notification and let him try to enter the right value.
Here are some examples how to deal with user input manually - https://stackoverflow.com/a/3059367/1916536. This is helpful to teach yourself.
Try to generalize user input operations:
name = validatedReader.readPhrase("name: ");
year = validatedReader.readNumber("year: ");
genre = validatedReader.readWord("genre: ");
where ValidatedReader is a custom wrapper for Scanner which could use your own validation rules, and could gently re-ask user after a wrong input.
It could also validate dates, phone numbers, emails, url's or so
For production purposes, it is better to use validation frameworks with configurable validation rules. There are a lot of validation frameworks for different purposes - Web, UI, REST etc...
when i enter the addMovie option, i get this print on the console (name: year:) can someone explain me why it happens i already searched a lot and i cant understand why :S
The way i understood your question is that you are getting the output (name: year: ) in a line and want it in seperate lines? In that case you simply can use System.out.println(String); instead of System.out.print(String). On the other hand you can also use "\n" whenever you want a linebreak within a String. Hope i could help you :).
Edit: If this was not an answer to your question, feel free to tell me and clarify your question :)
For String name you are using in.nextLine(); i.e the data entered on the entire line will be added to name string.
After "name: " is displayed, enter some text and press enter key, so that the year and gender fields will get correct values.
The code written is correct but you are not giving appropriate input through the scanner.
I recommend to use
String name = in.next();//instead of String name = in.nextLine();
You may instantiate Scanner Class differently for String and Integer type input. It works for me :)
Example:
static Scanner in1 = new Scanner(System.in);
static Scanner in2 = new Scanner(System.in);
Please use nextLine() for 'name' and 'gender'. It may contain more than one word. Let me know if it works.
Example:
System.out.print("name: ");
name = in1.nextLine();
System.out.print("year: ");
year = in2.nextInt();
System.out.print("gender: ");
gender = in1.nextLine();
So I have a file which has all presidents in it - their first name, middle initial (if any), and last name.
The file needs to be read in, and a user can enter a president's name to search for it, and that president should be displayed.
I have it displaying the president if a user searches by first name or by last name, but not by both.
For example, the external file contains:
George,Washington,(1789-1797)
Franklin,D.,Roosevelt,(1933-1945)
... and so on with all the presidents
I need the user to be able to either type in the first name, the last name, or both first and last name and get the desired result (the date is irrelevant for the most part).
Tried lots of different things, but not getting there as far as displaying the president if user searches by first and last name.
Here is what I got so far:
public class NameSearch {
public static void main(String[] args) throws IOException {
try {
// read from presidents file
Scanner presidentsFile = new Scanner(new File("Presidents.txt"));
// scanner for user input
Scanner keyboard = new Scanner(System.in);
// create array list of each line in presidents file
ArrayList<String> presidentsArrayList = new ArrayList<String>();
// prompt user to enter a string to see if it matches with a president's name
System.out.println("Enter a search string of letters to find a president match: ");
// store user input
String userInput = keyboard.nextLine();
// add president file info to array list linesInPresidentFile
while (presidentsFile.hasNextLine()) {
presidentsArrayList.add(presidentsFile.nextLine());
} // end while loop
String presidentNamesArray[] = presidentsArrayList.toArray(new String[presidentsArrayList.size()]);
String results = searchArray(presidentNamesArray, userInput);
//System.out.println("\nThe presidents who have \"" + userInput + "\" as part of their name are: ");
} catch (FileNotFoundException ex) {
// print out error (if any) to screen
System.out.println(ex.toString());
} // end catch block
} // end main
// method to search for a specific value in an array
public static String searchArray(String array[], String value) {
for (int i = 0; i < array.length; i++) {
if (array[i].toLowerCase().contains(value.toLowerCase())) {
String splitter[] = array[i].split(" ,");
System.out.println(Arrays.toString(splitter));
}
}
return Arrays.toString(array);
}
}
There is another way in which I might have implemented this.Read the file inputs and stored them as objects (class with lname, fname and year perhaps). In this way you can search for lname from user input, match it up with its corresponding fname (as same objects). The creation can be done once and searching can be done in a while loop implementing users consent of continuing the search.
//define your class like this:
static int i; //to keep a track of number of objects
public class dummy{
string fname;
string lname;
string year;
};
while the file content exists:
read the line
dummy dobj[i++] = new dummy();//allocate memory for the object
split the different parameters (fname, lname, year) from the read line
put these read parameters into the object
dobj[i].fname = first;
dobj[i].lname = second;
dobj[i].year = y;
//ask your user to enter the query in a specified format
//if he enters lname, compare your input to all the object's lname, and so on
//in case of lname && fname, compare your input to the lname first and then check for the corresponding objects fname, if they match.. display
Actually, there are many ways in which you can achieve what you wish to program. You can ask use the array list indices to solve it. If you take in the input from the user in a particular format, you can map it to the index in that list. Further, if you want to use first name and last name together, you may use these index representing the first and last name to come from same list.
The reason you may have problems searching by both first and last names is because you have to match your input exactly (ignoring case of course). What I mean is if you use George Washington as input, your program will not find a match for the George,Washington,(1789-1797) line. This is because your program treats George Washington as one string. Note: the input is missing the comma, so it will not be considered a substring of George,Washington,(1789-1797). If you used George,Washington as your input string, then your program would print the George Washington line. Your program just searches if the input string is a substring of any of the lines in your file. It does not search for a first name or last name specifically. If you used in as your input string, then you would get a match for both George Washington and Franklin D. Roosevelt.What you could do is take your input data and split it and search for each of the terms. You can either accept lines that match all of the terms provided, or at least one of the terms provided.
public static String searchArray(String array[], String value) {
// Uses both blank spaces and commas as delimiters
String[] terms = value.toLowerCase().Split("[ ,]");
for (int i = 0; i < array.length; i++) {
String line = array[i].toLowerCase();
boolean printIfAllMatch = true;
boolean printIfAtLeastOneMatches = false;
for(int j = 0 ; j < terms.length; j++) {
// Check that all terms are contained in the line
printIfAllMatch &= line.Contains(terms[j]);
// Check that at least one term is in the line
printIfAtLeastOneMatches |= line.Contains(terms[j]);
}
String splitter[] = array[i].split(" ,");
if (printIfAllMatch) {
System.out.println(Arrays.toString(splitter));
}
if(printIfAtLeastOneMatches) {
System.out.println(Arrays.toString(splitter));
}
}
//I'm not sure why you're returning the original array as a string
//I would think it would make more sense to return an Array of filtered data.
return Arrays.toString(array);
}
This does not take name ordering into account. If that's what you're going for, then I would suggest making a class and parsing each line in the file as an new object and trying to match the first term provided with the first name and second term provided with the last name, or something to that effect.
For this program it asks for the user to input their full name. It then sorts out the first name and last name by separating them at the space the put between the first and last name. However, indexOf() is not recognizing the space and only returns -1. Why is that? Thanks.
Here is the prompt off of PracticeIt:
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String fullName = inputScanner.next();
int space = fullName.indexOf(" "); // always return -1 for spaces
int length = fullName.length();
String lastName = fullName.substring(space+1,length+1);
String firstname = fullName.substring(0, space);
System.out.print("Your name in reverse order is " + lastName + ", " + firstname);
}
}
As next will return the next token use nextLine not next to get the whole line
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
When you do String fullName = inputScanner.next() you only read till the next whitespace so obviously there is no whitespace in fullName since it is only the first name.
If you want to read the whole line use String fullName = inputScanner.nextLine();