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.
Related
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);
}
}
I'm trying to create a program that parses through an input and determines whether or not it is a palindrome. Pasted below is my code so far:
import java.util.Scanner;
//Gets a message and shift amount and caesar shifts the message by the desired amount. Displays the enciphered message.
public class RobustPalChecker{
public static void main(String[] args){
//declare variables
char current, currentReverse;
int msgInt;
String msg, msgReverse;
StringBuffer sbMsg, newMsg;
Scanner sc = new Scanner(System.in);
//get message
System.out.println("Please enter an integer: ");
msg = sc.nextLine().toUpperCase();
//msgReverse = new StringBuffer(msg).reverse().toString();
System.out.println(msg);
//System.out.println("= " + msgReverse);
//get first and last index of string to check if it's a palindrome
for(int i = 0; i < msg.length(); i++) {
current = msg.charAt(i);
if(Character.isLetter(current) == false){
sbMsg = new StringBuffer(msg);
newMsg = sbMsg.deleteCharAt(i);
msgReverse = new StringBuffer(newMsg).reverse().toString();
}
}
if(newMsg.equals(msgReverse)) {
System.out.println("It's a palindrome");
}else {
System.out.println("It's not a palindrome");
}
}
}
Ignore comments as some of them don't apply and I have not cleaned it up yet. The line of code that I'm pretty sure is causing the error is the isLetter line. The goal of that loop is to find any character that is not a letter and just delete it, and that includes whitespace. That last if statement is the one that actually compares the reversed string and regular string. Now the output that the last if statement is giving me when I try to compile is "variable newMsg might not have been initialized" and the same for msgReverse, but that's not my main question.
My main question is: Is my logic here correct or incorrect?
Also, if you need me to rephrase the question, I can do that as I understand this might be hard to follow, I'm just panicking a little.
Your logic seems fine, but since code is not at all upto the mark its difficult to verify. I have written code in english commented format, if you are able to fill in the blanks all will fall in place.
Let's breakdown the problem in two sections :
Remove unwanted characters from string
Check if string returned from step1 is a pallindrome.
Create two functions :
String cleanUp(String arg){
//create a stringbuffer from arg
//start for loop
//delete unwanted chars from stringbuffer
//end loop
//make string from stringbuffer and return
}
boolean pallindrome(String arg){
//create a new string from arg reverse
//return true if reversed string and arg are same
}
Now call these functions from your main method.
I'm currently doing a project in my computer science class and we are suppose to validate each character of a variable to see if it is legal or not. If it starts with a number it's illegal. If it starts with a special character it's legal but bad style. If it has a space it is again illegal. I'll post my current code now:
import java.util.Scanner;
public class classOfValidation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String theVariable = null;
System.out.println("This program checks the validity of variables");
System.out.println("Please enter a variable (or press 'q' to quit");
theVariable = scan.nextLine();
do {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
} while (theVariable.startsWith("[0123456789]"));
do {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
} while (theVariable.contains("[ ]"));
do {
System.out.println("The variable is legal, but has bad style");
theVariable = scan.nextLine();
} while (theVariable.startsWith("[!##$%^&*]"));
}
}
If you couldn't already tell i'm new to programming and as confused as i possibly could be. If you have any advice or anything else you need me to explain then please leave a comment. Thanks everyone
You can use the single regex to validate your input via String#matches() method. But as for the example you've provided, you should use while loop, but not do-while, because in do while case, you are always running it's body once befor condition checked. So, you better do it like:
theVariable = scan.nextLine();
while (theVariable.startsWith("[0123456789]")) {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
}
while (theVariable.contains("[ ]")) {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
}
while (theVariable.startsWith("[!##$%^&*]")) {
System.out.println("The variable is legal, but has bad style");
theVariable = scan.nextLine();
}
The second, in your solution, you are using String.startsWith() method and passing into it some regex. Take a look at javadoc for this method. It's said there:
Tests if this string starts with the specified prefix.
That means, that this method doesn't support regexes, but simply checks whether the string starts with the passed string. So, your conditions seems, never to become true. I don't think, someone will input the [0123456789] or [!##$%^&*].
One more, any conditions are checked once, but after that user can modify the input and the previewsly passed condition will not be checked again. Seems, it's better to run into infinite loop with continue and break in some conditions, like:
//infinit loop, until user enter the `q` or the input is correct
while (true) {
//read the input
theVariable = scan.nextLine();
//chtck, whether is `quit` command entered
if ("q".equals(theVariable)) {
break;
}
//if string starts with digit or contains some whitespaces
//then print alert and let the user to
//modify the input in a new iteration
if (theVariable.matches("^\d+.*|.*\s+.*")) {
System.out.println("The variable is illegal");
continue;
}
//if string contains some special characters print alert
//and let the user to modify the input in a new iteration
if (theVariable.matches("^[!##$%^&*].*")) {
System.out.println("The variable is legal, but has bad style");
continue;
}
//if all the conditions checked, then break the loop
break;
}
I think the best way if you are use regex.
Here is an answer how to do that.
I'm making a program that reads a person's name and age, and when "zzz" is entered, it prints the names and ages of everyone who's 18 or older. Also, I want to calculate the percentage of people who's 18 or older. But, here's the problem: the code i'm posting bellow, only prints the first name (example: "Ricardo Almeida" and age "19". Output: "Ricardo : 19", but i want "Ricardo Almeida : 19). The percentage calculation has a error too but i cant figure out whats wrong. It gives 0 all the times. (DONE!) Thanks in advance to anyone who's reading this and trying to help.
PS: I dont want to use arrays! I already learned how to use them, but i want to know how to solve this without using them :)
package javaapplication38;
import java.util.Scanner;
public class JavaApplication38 {
private static final Scanner in=new Scanner(System.in);
private static String metodo1(String name, int age) {
String frase="";
if (age==18 | age>18) {
frase=String.format("%s : %d %n",name,age);
}
return frase;
}
public static void main(String[] args) {
int age, counter1=0, counter2=0;
String name, acumtxt="", aux;
do {
System.out.print("Name: ");
name=in.next(); in.nextLine();
if (!"ZZZ".equalsIgnoreCase(name)) {
counter1++;
do {
System.out.print("Age: ");
age=in.nextInt();
} while (age<=0);
if (age==18 | age>18) {
counter2++;
}
aux=metodo1(name,age);
acumtxt+=aux;
}
} while(!"ZZZ".equalsIgnoreCase(name));
System.out.print(acumtxt);
if (counter1>0) {
System.out.println("The percentage of people who's 18 or older is "+ (counter2/counter1) +"%.");
}
}
}
It seems that your problem is here
name=in.next(); in.nextLine();
In this code next() reads and returns only one word from line until it finds whitespace or end of line. Rest of it is consumed with readLine(), but you ignore its result. Try maybe to with
name=in.nextLine();
to read entire line.
After that you will also have to change
age=in.nextInt();
and either use
age=Integer.parseInt(in.nextLine());
or add in.nextLine() after it to also consume new line marks which would affect next name question.
age=in.nextInt(); in.nextLine();//add in.nextLine(); to consume new line marks
in.next() will read until there is a whitespace. You can use in.nextLine (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()) or use [BufferedReader](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html) instead, and you can call the readLine() method.
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 String saysSecret(String line){
if(secret.equals(line)){
return("You have won $100! The secret word is: " + secret);
}
else{
return("false");
}
}
public void main(String[] args){
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Groucho g = new Groucho(line);
while (in.hasNextLine()) {
Scanner input = new Scanner(System.in);
String guess = input.nextLine();
saysSecret(guess);
}
}
}
I thought his should work but when I run it I get:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Could someone explain what I am doing wrong?
Many thanks!
Miles
Add the static keyword to the main method so that the application has a valid entry point
As saySecret is an instance method, it needs to be invoked as such, replace
saysSecret(guess);
with
g.saysSecret(guess);
You may also want to change your while loop to something like this:
while (in.hasNextLine()) {
String guess = in.nextLine();
String answer = g.saysSecret(guess);
System.out.println(answer);
}
No need to create a new Scanner each time. Also, you have to call saysSecret on the g instance, as it is not static. Finally, the saysSecret method only returns an answer, but you still need to print it.
However, this will still loop forever, waiting for user input. It would be better to modify your saysSecret method to return a boolean and exit the loop once this boolean is true, i.e., the guess was correct.