How do I create a name generator? - java

I am creating a program that prompts a first and last name then prints a string composed of the first letter of the user’s first name, followed by the first five characters of the user’s last name, followed by a random number in the range 10 to 99.
I know how to prompt for the name and find the random number but I'm not sure how to
"print a string composed of the first letter of the first name, followed by the first five letters of the last name."
Can anyone help me? I am a very elementary Java programmer.
So I am really close to finishing this but it keeps saying "illegal start of expression" for line 55 and I can't figure it out. Here is my code, sorry, I know it's a mess:
Random generator = new Random();
int num1;
num1 = generator.nextInt(10-99);
line 55: public String substring; <<<
String result;
System.out.println("Result:" + (beginIndex) + (firstname.substring(0,1) + lastname. substring (0,5)) + (num1) );

Seems like homework to me, so I will give a hint. look for the method substring() and charAt() for the first part, and the Random class for the second.

I am a .NET developer so I can't help you with the syntax but you would need to grab the first char of the first name, usually accessible via an indexer - firstName.charAt(0), and a substring of the second one that ranges from the first character (ordinal 0) to the 5th character (ordinal 4), likely something like lastName.substring(0, 4); and concatenate these two strings -
concatenatedName = firstName.charAt(0) + lastName.substring(0, 4);

Something like this will do
import java.lang.String;
import java.io.*;
import java.util.Random;
class Name {
public static void main(String args[]) {
Random rnd = new Random(); // Initialize number generator
String firstname = "Jessica"; // Initialize the strings
String lastname = "Craig";
String result; // We'll be building on this string
// We'll take the first character in the first name
result = Character.toString(firstname.charAt(0)); // First char
if (lastname.length() > 5)
result += lastname.substring(0,5);
else
result += lastname; // You did not specify what to do, if the name is shorter than 5 chars
result += Integer.toString(rnd.nextInt(99));
System.out.println(result);
}
}

You're missing a closing parentheses for println.
I would recommend removing all the parentheses around the string concats they just make it hard to read.
System.out.println("Result:" + beginIndex + firstname.substring(0,1) + lastname.substring(0,5) + num1 );
Also what happens if the user enters a last name with only 4 characters?

Take a look at String.substring()

See how easy it is? I gave 4 simple names which can be replaced with words and such. The "4" in the code represents the number of names in the String. This is about as simple as it gets. And for those who want it even shorter(all I did was decrease the spacing):
import java.util.*;
public class characters{
public static void main(String[] args){
Random generate = new Random();
String[] name = {"John", "Marcus", "Susan", "Henry"};
System.out.println("Customer: " + name[generate.nextInt(4)]); }}

Related

Replace last two letters in Java

I am asking for help on this code that I am making, I want it to replace the last two letters. I am coding a program that will:
Replace four letter words with "FRED"
Replace the last two letters of a word that ends with "ed" to "id"
Finally, replace the first two letters if the word starts with "di" to "id"
I am having difficulty with the second stated rule, I know that for number 3 I can just use replaceFirst() and to use the length for the first rule, but I am not sure how to specifically swap the last two characters in the string.
Here is what I have so far:
package KingFred;
import java.util.Scanner;
public class KingFredofId2 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String king = input.nextLine();
String king22 = new String();
String king23 = new String();
if(king.length()==4)
{
System.out.println("FRED");
}
String myString = king.substring(Math.max(king.length() - 2, 0));
if (myString.equals("ed"))
{
king22 = king.replace("ed", "id");
System.out.println(king22);
}
if(true)
{
king23 = king.replace("di", "id");
System.out.println(king23);
}
}
I am new to Stack Overflow, so please let me know how I can make my questions a little more understandable if this one is not easily comprehended.
Thanks.
There may be a way to more optimally combine the regular expressions, but this will work.
\\b - word boundary (white space, punctuation,etc).
\\b(?:\\w){4}\\b - four letter word
ed\\b - word ending with ed
\\bdi - word starting with di
replaceAll(regex,b) - replace what regex matches with string b
String s =
"Bill charles among hello fool march good deed, dirt, dirty, divine dried freed died";
s = s.replaceAll("\\b(?:\\w){4}\\b", "FRED")
.replaceAll("ed\\b", "id")
.replaceAll("\\bdi", "id");
System.out.println(s);
prints
FRED charles among hello FRED march FRED FRED, FRED, idrty, idvine driid freid F
RED
This is the most simplest way I could think to solve the second case of replacing the last two characters.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line or a word: ");
String s = sc.nextLine();
//getting the length of entered string
int length = s.length();
//initializing a new string to hold the last two characters of the entered string
String extract = "";
//checking if length of entered string is more than 2
if (length > 2) {
//extracting the last two letters
extract = s.substring(length - 2);
//updating the original string
s = s.substring(0, length - 2);
}
//checking if the last two characters fulfil the condition for changing them
if (extract.equalsIgnoreCase("ed")) {
//if they do, concatenate "id" to the now updated original string
System.out.println(s + "id");
} else {
//or print the originally entered string
System.out.println(s + extract);
}
}
}
I believe the comments are giving enough explanation and further explanation is not needed.

charAt never works correctly from Scannner input

this is my code....and problem I need to have an input from user where the first letter is used , then from the second user input from 0 to 5 the characters are used, and finally generate a random number....I have tried everything for the second portion (0 to 5 characters) and I've searched the internet for different answers but nothing works.
here is the source code :
//********************************************************************
// NameNumberConverter.java Java Foundations
//
//
//********************************************************************
import java.lang.*;
import java.util.Scanner;
import java.util.*;
public class NameNumberConverter
{
//-----------------------------------------------------------------
// First the user inputs their first and last names
//-----------------------------------------------------------------
public static void main(String[] args)
{
Scanner sc = new Scanner( System.in );
System.out.println ("Please insert your first name : ");
String Firstname=sc.next();
System.out.println ("Please insert your last name : ");
String Lastname=sc.next();
char end = Firstname.charAt(0);
char end2 = Lastname.charAt(0, 5);
System.out.println ("The converted result is: " + end + end2);
sc.close();
}
}
Thanks for anything that can be helpful. as I am a student and definitely not a pro....
Unfortunately charAt(int) only takes one integer parameter.
I think what you are looking for is the range of characters for the last name. You can do something like this to get characters within a specific range for a string.
// string variable for example
String exampleString = "J. Smith";
// here is how to get a range of characters with substring(int,int)
String lastName = exmapleString.substring(3,7);
// print out "Smith"
System.out.println(lastName);
Now remember that the index value of strings starts at [0]

print even words from string input?

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());
}
}

Print random characters from string

I want to print three random characters, chosen from a given string. But I have no idea how to do random things like this!
See the "Bonus Opportunity" in this question.
Here is my code, split into 2 parts with the extra credit part being on the right side.
It depends on what "random" means in this case.
Weighted probability
If repeating characters should be given a higher chance of being chosen, simply concatenate the first name, middle name, and last name into one string:
String s = first + middle + last;
Then generate a random number between 0 and the length of the string:
Random r = new Random();
int R = r.nextInt(s.length());
Use this random number to index the particular character:
output_character = s.charAt(R);
Repeat as many times as desired.
Equal probability
If each of the characters are to have the same probability as the others, you will need to push unique characters into a list and repeat the same procedure as described above.
It is a little dishonest, academically, to ask for the solution to a homework question. It would be a bit less problematic if you'd do a little thinking on your own.
As #Zar mentioned in the comment above, asking something like "How do I get a random character in Java" would be simpler, and would give you what you need to answer the question without asking someone else to hand it to you.
import java.util.Random;
public class RandomAddingTest {
public static void main(String[] args){
System.out.println(returnNewPass("abcabc"));
//display something like:[abcabcwMS][abcabcCln][abcabc?p=]...so on
}
public static String returnNewPass(String oldPass){
StringBuilder sb = new StringBuilder(oldPass);
Random ran = new Random();
char c ;
for (int i = 0; i<3; i++){
c = (char)(ran.nextInt(93)+33);//ran will generate A~Z,a~z,0~9,##$%^&*...so on
sb.append(c);
}
return sb.toString();
}
}

Finding the index of each character in a substring

I feel like my logic is decent here; I don't feel like I'm completely lost. However, I do know what exactly I'm doing wrong. I can always find the index of the start of the substring, but I can never find the full count (ex. 3,4,5,6) of the index of whatever word the user enters as the substring.
I have been struggling with this for about a week trying to figure out how to do it on my own, I can't get it right.
import java.util.Scanner;
public class midterm
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String simplePhrase;
String portionPhrase;
int portionIndex;
int portionCount;
int portionIndexTotal;
System.out.println("Enter a simple phrase:");
simplePhrase = keyboard.nextLine();
int phraseLength = simplePhrase.length();
System.out.println("Phrase length:" +phraseLength);
System.out.println("Enter a portion of previous phrase:");
portionPhrase = keyboard.nextLine();
String portionPhraseSub = simplePhrase.substring(portionPhrase);
portionIndex = simplePhrase.indexOf(portionPhraseSub);
for (portionIndex; portionIndex <= portionPhrase; portionIndex++)
{
System.out.println("Portion phrase index:"+portionIndex);
}
}
}
I'm still confused on what you want. There are just two simple things to know and you seem to be making this more complicated than it needs to be.
To get the index of a single character, such as "c" in the word "acorn", you would do this:
String s = "acorn";
int cIndex = s.indexOf("c");
System.out.println("The index of c is: " + cIndex);
If you want to see if the string contains a chunk, you use the exact same method. So if we are looking at the word "acorn" again and you want to see where "orn" happens, you'd do this:
String s = "acorn";
int ornIndex = s.indexOf("orn");
System.out.println("The index of orn is: " + ornIndex);
Remember that indexes start from 0 in java, so the index of "a" in "acorn" is 0, of "c" is 1, of "o" is 2, and so on.
I hope that helps. Good luck :)
EDIT: You just commented this:
"I guess, my question is one i get my code to compile, How would I go about counting every single letter of my substring?"
I'll answer that as best as I can, though again, that still is a confusing question.
What do you even mean by count" every letter? If you want to break your word into individual letters, you can do something like this:
String s = "acorn";
char[] characters = new char[s.length()-1];
for(int i = 0; i < s.length() - 1; i++) {
char[i] = s.charAt(i);
}
But I have no clue why you'd want to do that...you can always access any character in a string at a given index with STRING.charAt(index), or if you want to have a String result, STRING.substring(index, index+1)

Categories

Resources