I'm not sure where I am going wrong with this particular code. Could someone please lend me some guidance to this?
Here is my question as well as what I have attempted to have as an outcome.
Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.
Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints:
Banana-fana fo-fatie!
Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints:
Fee fi mo-matie
Note: You may assume songVerse will always contain the substring "(Name)".
Code that I tried this last time...and no matter what I put in I keep getting the same results. I've tried different scenarios of the "userName.substring()" and still have the same outcome.
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1 test passed
All tests passed
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
Here you go.
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}
}
here you removed first character already from userName, so at the second last line you again don't need to remove it.
and for the song Verse, you need to remove "(NAME)" from it, so here you can use
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
The method substring(int begin, int end) let hoose/create a substring from the initial String indicating the numbers of chars from which the substring should begin and end or begin only. There are no other variants to edit a substring, while it will not become a part of a freshly made string (“String songVerse” in your case). The object.replace() method should change the indicated “Text” (in your case it’s a “(Name)”) onto anything that you’d like to be inserted instead of it independently on the quantity or type of the chars before or after the “Text”. The variant proposed by Nicholas K is correct and should work or you can try its shorter version, however the result will be the same:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
The problem with your code is that you are not attempting to solve the problem that you described in your question.
Try following these steps:
Devise a list of steps written in English to solve the problem; pay attention to details.
Run the list of steps in step 1 by hand.
Convert the steps in step 1 to code.
Here are some hints:
You will be reading the lyrics one line at a time.
Some lines have a replacement and others do not.
You will receive the Name as input one time; generate the name replacement value one time and use it each time you perform a replacement.
Your code is terrible.
Here is some more about "Pay attention to details"
You do not have a loop in your code;
this will read one line of lyrics and perform one substitution.
Count the number of lines in the lyrics.
If the number of lines is greater than one,
then your technique is guaranteed to fail.
If you have a loop in your code but decided not to include it in your code,
stop lying in your questions.
We can not help you fix code that you pretend does not exist.
In a sane world,
the name to use for the substitutions will appear exactly one time.
Read it one time.
In order to replace (Name) in a string, you must first find (Name) in a string.
This is pretty easy
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName);
/* Your solution goes here */
System.out.println(songVerse);
}
}
Related
I am supposed to use the Scanner in Java to receive a 14 char input and have all the letter char output in uppercase format. I've tried entering some of the code I found through Google such as " str.toUpperCase(Locale.ENGLISH); " but it tells me str cannot be resolved and that the locale can't be resolved. When I did a search on here I got results for uppercasing specific char or counting char. I just need the specific line of input to be uppercased.
The following is what I have at the moment. I am using eclipse java neon
import java.util.Scanner;
public class MemberIDLotz {
// Everette Lotz
public static void main(String[] args) {
Scanner string = new Scanner(System.in);
// We're going to get a 14 char string from a user.
System.out.println("Please enter in a 14 character long ID");
String name = string.next();
str.toUpperCase(Locale.ENGLISH);
string.close();
}
}
Thank you for your help in advance.
*Edit: Ok so it is no longer giving me an error message, and yes I had simply copy and pasted the code. However when it prints out its not in upper case format. I put the following right after "String name =...." and deleted the str.toUppercase() line:
System.out.println(name);
name = name.toUpperCase();`
Is there a reason you don't uppercase immediately?
String name = string.next().toUpperCase()
Change to
name = name.toUpperCase(Locale.ENGLISH);
or more simply
name = name.toUpperCase();
You can also add trim to it if you'd like, it is a working example:
String choice;
Scanner s = new Scanner(System.in);
choice = s.nextLine().trim().toUpperCase();
I am trying to make a program that allows the user to input 2 different formats for a postal code (A1A1A1 or A1A 1A1) and I cannot for the life of me get it to work :/
My thought process was identifying both formats first and then using an if statement to check for the identified formats and then decide if its valid or not.
But I keep getting invalid when I try to enter the format with space in them (A1A 1A1).
so far I have this
import java.util.Scanner;
import java.util.regex.Pattern;
public class ValidatingPostcodes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Postcode:");
String Pc1 = "[A-Z][0-9][A-Z][0-9][A-Z][0-9]";
String Pc2 = "[A-Z][0-9][A-Z][ ][0-9][A-Z][0-9]";
while (sc.hasNext())
{ if (sc.hasNext (Pc1))
System.out.println ("Valid Postal Code");
else if (sc.hasNext (Pc2))
System.out.println ("Valid Postal Code");
else System.out.println("Invalid Postal Code");
sc.next();
}
}
}
The easy solution is: simply treat the two kinds of input the same way when processing them internally. Meaning:
Create one method that validates a 6-char potential ZIP code
But before calling that method, you check if your input contains a space as 4th character, and if so, you simply remove that space before giving it as parameter to your validation method.
But keep in mind: you probably want to keep the original string around - if you intend to give back "A1A A2A" later on. Of course, if you decide that users can enter ZIPs in two ways, but that they should get back "unified" format later on, then you can make that "space-dropping" thing permanent.
EDIT: you create a method
public boolean isValid(String zipCode) {
that returns TRUE for valid zipcodes that have 6 (SIX!) chars and no spaces
and another method
public String normalizeZipCode(String incoming) {
return incoming.replaceAll("\\s+","");
}
To be used like:
String zip1 = "A1A 1A1";
String zip2 = "A1A1A1";
String normalizedZip1 = normalizeZipCode(zip1);
String normalizedZip2 = normalizeZipCode(zip2);
System.out.println(isValid(normalizedZip1));
System.out.println(isValid(normalizedZip2));
The simple idea: if one format contains spaces, then just remove those spaces prior validation. In other words: you allow the user to enter data in two formats; but internally, you make sure that any usage of the second format is simply avoided, by turning it into the format that comes without spaces.
So far I have been able to censor "cat", "dog" and "llama". Now I just need to make the exception of "Dogmatic" but cannot figure it out for the life of me. Below I have attached what I have so far. Please any suggestions will help really.
/* take userinput and determine if it contains profanity
* if userinput contains profanity, it will be filtered
* and a new sentence will be generated with the word censored
*/
keyboard = new Scanner(System.in);
System.out.println("Welcome to the Star Bulletin Board!");
System.out.println("Generate your first post below!");
String userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
if (userInput.indexOf("cat") != 15){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("cat", "***"));
}
else
System.out.println(userInput);
if (userInput.indexOf("dog") != -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("dog", "***"));
}
if (userInput.indexOf("llama")!= -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("llama", "*****"));
}
You can use a word boundary \\b. Word boundaries match the edges of a word, like spaces or punctuation.
if (userInput.matches(".*\\bdog\\b.*")) {
userInput = userInput.replaceAll("\\bdog\\b", "***");
}
This will censor "Don't be a llama." but it won't censor "Don't be dogmatic."
userInput.matches(".*\\bdog\\b.*") is a slightly better condition than indexOf/contains because it has the same match as the replacement. indexOf/contains would still show the message despite not censoring anything. .* matches any character (except typically new lines), optionally.
Note: this is still not a very effective way to filter profanity. See http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/.
Use word boundaries. Take a look at the following code; it will print true for all cases except the last one:
String a = "what you there";
String b = "yes what there";
String c = "yes there what";
String d = "whatabout this";
System.out.println(Pattern.compile("\\bwhat\\b").matcher(a).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(b).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(c).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(d).find());
You can combine all your bad words into a single regex like so:
Pattern filter = Pattern.compile("\\b(cat|llama|dog)\\b");
This is fine for simple cases, but for a more robust solution you probably want to use a library. Take a look at this question for more information.
I'm trying to understand file I/O for class and I understand the basics but I'm having trouble understanding how to manage whats in the input file, the input file is formatted like this:
BusinessContact:firstName=Nikolaos;lastName=Tsantalis
SocialNetworkAccount:socialNetworkType=SKYPE;accountID=tsantalis
Basically my contact (which BusinessContact extends from) object has attributes of firstName, lastName and middleName,
it also has object attributes such as SocialNetworkAccount and such....
I don't need to be explained how my objects are formatted, those have been done all I'm trying to understand is how my file.txt in inputed into my program to set my Contact to a BusinessContact as well as setting the first and last name accordingly,
Thanks
EDIT: Im specifically told to use the split method which makes sense but I'm also told (1) create a common method for the parsing of attributes that returns a map where the keys correspond to the attributeNames and the values to the attributeValues (in this way you can reuse the same code)
You can use the Scanner class with different delimiters like below:
Scanner in = new Scanner(/**source*/);
in.useDelimiter(":");
String firstName, lastName;
String firstWord = in.next();
Scanner nameScanner = new Scanner(in.nextLine());
nameScanner.useDelimiter(";");
firstName = getName(new Scanner(nameScanner.next()));
lastName = getName(new Scanner(nameScanner.next()));
private String getName(Scanner nameScanner){
nameScanner.useDelimiter("=");
String nameTitle = nameScanner.next();
return nameScanner.next();
}
This way you read the text in parts as follows as follows:
BusinessContact:firstName=Nikolaos;lastName=Tsantalis
firstName=Nikolaos;lastName=Tsantalis
firstName=Nikolaos;lastName=Tsantalis
I hope this makes sense.
NOTE: This code reads only the first line. If you want to read the second i guess its not hard to modify it. If you want the second line too or if you have any issues let me know and i will update the answer.
EDIT: I just noticed that every line is formated the same way so basically you can use the same code for every line. Maybe in a loop like:
Scanner input = new Scanner(/**source*/);
while(input.hasNextLine()){
Scanner in = new Scanner(input.nextLine());
...
....
//The above code
}
String.split() method:
Scanner in = new Scanner(System.in);
String[] first = in.nextLine().split(":");
String[] second = first[1].split(";");
String[] thirdA = second[0].split("=");
String[] thirdB = second[1].split("=");
for(int i = 0; i < thirdA.length; i++){
System.out.println(thirdA[i]);
System.out.println(thirdB[i]);
}
For the first line, the above code will print:
firstName
lastName
Nikolaos
Tsantalis
Hope this helps.
You could use a regular expression, but you might feel more comfortable with String.split: Split on ":" and get the label, the split the second part on ";" to get the attributes, then split each attribute on "=" to get the key and the value.
Apologies for posting about this topic twice today, this one is a different question. So I am working on a java problem at the moment where I am creating a program that simulates the old TV quiz show, You Bet Your Life. The game show host, Groucho Marx, chooses a secret word, then chats with the contestants for a while. If either contestant uses the secret word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code:
import java.util.Scanner;
public class Groucho{
String secret;
Groucho(String secret){
this.secret = secret;
}
public boolean saysSecret(String line){
if(secret.equals(line)){
return(true);
}
else{
return(false);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Groucho g = new Groucho(line);
while (in.hasNextLine()) {
String guess = in.nextLine();
/*Not sure about these next two lines:
*String answer = g.saysSecret(guess);
*/System.out.println(answer);
}
}
}
When I run it nothing happens. I thought it should be returning true or false? What I would actually like it to do is if the line contains the secret word, it prints a message that says “You have won $100” and tells what the secret word is. Could anyone point me in the right direction?
Many thanks
Miles
As Sotirios points out, you should use saysSecret(String) to check if the guess is correct.
So the loop could look like:
while (in.hasNextLine()) {
String guess = in.nextLine();
if (g.saysSecret(guess))
{
System.out.println("You got it! The word was: "+g.secret);
} else {
System.out.println("Aw, try again.");
}
}
Your code does not work because you are assigning a boolean value to a String. You should compare the return value of g.saysSecret(guess), and then if this value is true print your successful message (or even print a failure message if this value is false).
Also, you have said:
What I would actually like it to do is if the line contains the secret word ...
so
secret.equals(line)
is not what you want since that will be true only if the entire line is equal to the secret word. For search for a word inside a line you could use:
line.contains(secret)
or maybe you need a more elaborated method for case insensitive matchs and so on.