Hello im a total beginner in Java and have a problem. In a code below that has an array of fixed list of guests, how can i print emails of these person? The email must consist of 3 first name digits and two first surname digits, and after these are #guest.com. So it looks like this:
adaro#guest.com
thost#guest.com
In this task i must use methods: substring, split, toLowerCase.
Sorry for my english its not perfect. Please help i've tried to solve this but i'm stuck cant manage it.
public class email {
public static void main(String[] args) {
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
}
}
When you are stuck like this, try breaking down the problem bit by bit.
You are saying you don't know how to extract part of string, but also how to print. I'm tempted to give you written instructions and not the full answer to your question because that's how you will learn better.
You need to construct this email for each String in the String[] array. Look for iterating over arrays in java here for example https://www.geeksforgeeks.org/iterating-arrays-java/
For each String which is of this form "Rock Adam" you need to extract the surname and last name. To do this you need to split the String by space " ". How to do that - How to split a String by space
When you split by space you will get another Array of two elements, first will be surname, second will be first name. Use array indecies to access them.
When you access the firstName your next problem is - how do I get the first 3 characters of that String. How to access 3rd or 2nd is the same problem see how to do this here Extract first two characters of a String in Java
Now that you have the substrings you want to know how to concatenate and print them. How to print multiple variables? Answer is here How to print multiple variable lines in Java. Also for transforming the strings to lowercase you can find answer here https://www.w3schools.com/java/ref_string_tolowercase.asp
Try to do some more work yourself following this and you will learn much more than from copy-pasting what someone will give you directly for free.
Lower code solves your problem. String.split(" ") splits the String at the first occurrence of blank space. It gives a String array back which contains both parts of the name. With String.substring() you can get specific parts of the String.
public static void main(String[] args) {
String[] guests = {"Rock Adam",
"Stewart Thomas",
"Anderson Michael"};
for(String guest : guests){
String[] name = guest.split(" ");
String email = name[1].substring(0,3).toLowerCase() + name[0].substring(0,2).toLowerCase() + "#guest.com";
System.out.println(email);
}
}
Below code is exactly what you are looking for (i guess)
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
List<String> emailIdList = new ArrayList<>();
for (String guest : guests) {
String firstName = guest.split(" ")[1];
String lastName = guest.split(" ")[0];
String emailId = firstName.substring(0,2) + lastName.substring(0,1) + "#guest.com";
emailIdList.add(emailId);
}
Related
I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}
Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}
I've researched this subject thoroughly, including questions and answers on this website....
this is my basic code:
import java.util.Scanner;
class StringSplit {
public static void main(String[] args)
{
System.out.println("Enter String");
Scanner io = new Scanner(System.in);
String input = io.next();
String[] keywords = input.split(" ");
System.out.println("keywords" + keywords);
}
and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]...
But whenever i compile this code, i get this output:
"keywords = [Ljava.lang.String;#43ef9157"
could anyone suggest a way for the array to be outputted in the way i require??
Sure:
System.out.println("keywords: " + Arrays.toString(keywords));
It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.
You could try using Java's String.Split:
Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.
As for output, use a for loop or foreach look to go over the elements of your array and print them.
The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.
This code should work:
String inputString = new String("hello, world, how, are, you, today");
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
words.add(scn.next());
}
//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
keywords[i] = words.get(i);
}
The useDelimiter function uses the comma to separate the words. Hope this helps!
I was looking for a little help as I'm at my wits end on how to accomplish this.
The assignment is to read in a file that contains state names, the governor of that state and the compensation he gets.
Example of the file:
California Tim John $50,000 $78,890 $30,000
North Dakota John Jones $30,000 $40,000 $56,000
Washington Susan K. Bones $30,000 $40,000 $56,000
As you can see, a name can contain more than three words (including the middle initial)
The output I'm supposed to get is the presidents name followed by the total compensation..
Example of output:
Susan K. Bones $126,000
I've already written code that prints out the total compensation. But I'm stuck on reading the names. How do I ignore the state names which can contain at most two words and just take the governor's name?
Here is my code for the total compensation.
Also note: I have to use Scanner on this.
Scanner in = new Scanner(file);
in.nextLine();
do {
double totalCompensation = 0.0;
String readLine = in.nextLine();
readLine = readLine.replaceAll(",", "").replace("$", " ");
String presidentName = "";
Scanner readNumber = new Scanner(readLine);
while(readNumber.hasNext()) {
if (readNumber.hasNextDouble())
totalCompensation += readNumber.nextDouble();
else {
readNumber.next();
}
}
Another note: don't worry, I do have a while(in.hasNextLine()) to close the do loop, later on in my code. I just don't really want to paste in the whole thing.
Any hints would be welcome! Thanks!
If you KNOW ahead of time that you will only ever see US state names, you could have your code look for a state name first. Since you know what part is the state name and what part is the compensation, whatever is left must be the governor's name. There's only 50 states, so this isn't impossibly difficult.
If this is more generic and can be a city/country/whatever and not just a US, there's not a way to distinguish without a better separator character (or quotes to define the "state name" and "governor name".
EDIT: You mention that there is a further requirement that the "leader" name will be of the form "Firstname LastName" "Firstname M. Lastname" or "F. Middlename Lastname". NOW you have enough to solve the answer.
As you pull strings out with the scanner, put them in a list (or if you learned this datatype, a stack is more appropriate). Go through the list backwards. If the 2nd element is an initial, you know the name has three parts. If the 3rd element is an initial, you know the name has three parts. If neither is an initial, you know the name has two parts. Whatever is not the name of the leader is the name of the place.
My previous answer utterly failed to use Scanner, which was a stated requirement. As before, I am using the "New," "North," etc, prefix to delineate two word state names.
static String[] TWO_WORD_STATE_PREFIXES = new String[] {"New", "Rhode", "North", "West", "South"};
public static void scanLine(String line) {
Scanner s = new Scanner(line);
String stateName = s.next();
for (String prefix : TWO_WORD_STATE_PREFIXES)
if (stateName.equals(prefix))
stateName += " " + s.next();
String governorName = "";
String nextToken;
while (!(nextToken = s.next()).startsWith("$"))
governorName += nextToken + " ";
governorName = governorName.trim();
int compensation = 0;
while (s.hasNext())
compensation += Integer.parseInt(s.next().replaceAll("[\\$, ]", ""));
System.out.println(stateName + " - " + governorName + " : " + compensation);
}
public static void main(String[] args) {
scanLine("California Tim John $50,000 $78,890 $30,000");
scanLine("Virginia Some Guy $55,000 $71,890 $30,000");
scanLine("South Carolina Bill F. Gates $91,000 $1,200");
scanLine("Vermont Joan Smith $60,000 $78,890 $30,000");
scanLine("North Dakota Tim John $50,000 $78,890 $30,000");
}
Can the file be modified to contain delimiters other than space like semi-colon. Otherwise one option i can think of is store the list of states and iterate through them and check other wise it would be a name. Eg.
List<String> stateNames={"Alabama","Alaska","Texas"};
This question is about efficient string searching. Let's work on determining which part of the string is the city or state name, since once you have that the rest is trivial.
First, you will need a list of cities and states. Here's a list of cities (should be pretty easy to parse out the actual city names) http://www.census.gov/tiger/tms/gazetteer/places2k.txt and I'm sure you can find a list of states somewhere.
Once you have that, here's a simple strategy for an efficient solution:
put the list of cities and states into a hashtable
split the input string (ex. "Califonia John Doe $213 $1232") by spaces
for each prefix of this list, check if the corresponding string is in the hashtable - if it is, then assume that's the state/city and parse the rest of the input accordingly.
Edit: nevermind - you added some information to the question that makes it much easier to solve. It's no longer an efficient string search problem- it's now a simple puzzle to help you practice looping in Java. See Kane's answer.
It's interesting how drastically just a little bit of information can change the scope of a problem :)
So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}