I am writing a java program that allows the user to get a song recommendation based on their current mood, but I am recieving this error when compling my code to check if runs correctly
java.lang.AssertionError:
Expected: a string containing "Welcome to the Music Recommender!\nDo you want to listen to a song?\nAre you feeling happy?\nDo you want to clap along?\nPlay \"Happy\" by Pharrell Williams\nThank you for using the Music Recommender!\n"
but: was "Welcome to the Music Recommender!
Do you want to listen to a song?
Are you feeling happy?
Do you want to clap along?
Play "Happy" by Pharrell Williams
"
public class MusicRecommender {
public static final String WELCOME_MESSAGE = "Welcome to the Music Recommender!";
public static final String INITIAL_SONG = "Do you want to listen to a song?";
public static final String HAPPY = "Are you feeling happy?";
public static final String CLAP_ALONG = "Do you want to clap along?";
public static final String SING_OUT = "Do you want to sing out?";
public static final String DANCE = "Do you want to dance?";
public static final String SAD = "Are you feeling sad?";
public static final String LYRICS = "Do you want lyrics?";
public static final String WORRIED = "Are you feeling worried?";
public static final String CALM = "Are you feeling calm?";
public static final String COMPLICATED = "Are your feelings more complicated" +
" than this program can handle?";
public static final String CONTINUE_WORRIED = "Do you want to keep " +
"feeling worried?";
public static final String GOODBYE_MESSAGE = "Thank you for using" +
" the Music Recommender!";
public static final String SONG_ONE = "Play \"Happy\" by Pharrell Williams";
public static final String SONG_TWO = "Play \"If you want to Sing Out, Sing Out\" by Cat Stevens";
public static final String SONG_THREE = "Play \"Uptown Funk\" by Mark Ronson featuring Bruno Mars";
public static final String SONG_FOUR = "Play \"La finta giardiniera, K. 196: Ouverture. Allegro molto\" by Mozart";
public static final String SONG_FIVE = "Play \"Hurt\" by Trent Reznor, as performed by Johnny Cash";
public static final String SONG_SIX = "Play Theme from Schindler's List";
public static final String SONG_SEVEN = "Play \"Aben bog\" by Bremer/McCoy";
public static final String SONG_EIGHT = "Play \"Complicated\" by Avril Lavigne";
public static final String SONG_NINE = "Play \"A Witch Stole Sam\" by Mark Korven" +
" from The Witch Original Soundtrack";
public static final String SONG_TEN = "Play \"Don't worry. Be Happy\" by Bobby McFerrin";
// ------------------------- DO NOT MODIFY ABOVE -------------------------
// IMPLEMENT YOUR SOLUTION HERE
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // intialize Scanner object
System.out.println(WELCOME_MESSAGE); // greeting to the user
System.out.println(INITIAL_SONG);
String userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("no")) {
System.out.println(GOODBYE_MESSAGE);
} else if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(HAPPY);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(CLAP_ALONG);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_ONE);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(SING_OUT);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_TWO);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(DANCE);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_THREE);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(SONG_FOUR);
}
}
}
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(SAD);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(LYRICS);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_FIVE);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(SONG_SIX);
}
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(WORRIED);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(CONTINUE_WORRIED);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_NINE);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(SONG_TEN);
}
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(CALM);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_SEVEN);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println(COMPLICATED);
userResponse = in.nextLine();
if (userResponse.equalsIgnoreCase("yes")) {
System.out.println(SONG_EIGHT);
} else if (userResponse.equalsIgnoreCase("no")) {
System.out.println("I am sorry, but you will need to seek further help.");
}
}
}
}
}
}
}
}
I have tried reformatting the strings, I am currently thinking I just need to add a new line character to the variables above, but I am not sure if that is really the problem, I am not sure what should be output to me, but hopefully I can be corrected thank you!
Related
Here's the first part:
package Week5;
class BloodData
{
private String bloodType;
private String rhFactor;
public BloodData()
{
bloodType = "O";
rhFactor = "+";
}
public void setBloodType (String bloodType){
this.bloodType = bloodType;
}
public void setRhFactor (String rhFactor){
this.rhFactor = rhFactor;
}
String getBloodType(){
return this.bloodType;
}
String getRhFactor(){
return this.rhFactor;
}
}
here's the main method:
package Week5;
import java.util.Scanner;
public class RunBloodData
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BloodData bd = new BloodData();
System.out.print("Enter blood type of patient : ");
bd.setBloodType(input.nextLine());
System.out.print("Enter the Rhesus factor (+ or -) : ");
bd.setRhFactor(input.nextLine());
if(bd.getBloodType().equals("") && bd.getRhFactor().equals(""))
{
bd = new BloodData();
System.out.println (bd.getBloodType().toUpperCase() + bd.getRhFactor() + " is added to the bloodbank.");
}
else
{
bd = new BloodData();
System.out.println (bd.getBloodType().toUpperCase() + bd.getRhFactor() + " is added to the bloodbank.");
}
}
}
NOTE: I HIGHLY SUSPECT THAT I HAVE TO PUT SOMETHING INSIDE of new bloodData in:
else
{
bd = new BloodData();
I just don't know what to call considering bloodType and rhFactor are private and non-static.
I fixed it, I just had to remove bd = new BloodData(); in my else statement so any input will be registered.
I know this is a very very common error but I am stuck on this one and I totally don't understand why is it happening.
Here is a part of my code
import java.util.ArrayList;
import java.util.Scanner;
public class Manager {
private static Scanner sc = new Scanner(System.in);
protected static ArrayList<String> identifications = new ArrayList<String>();
protected static String[] signIn() {
System.out.println("Hi !");
System.out.println("Welcome to School Management System");
System.out.print("Please enter your ID number : ");
boolean idValid = false;
String providedID = null;
int idListPosition = -1;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
while (idValid != true) {
for (String element : identifications) {
if (element.equals(providedID)) {
idValid = true;
idListPosition = identifications.indexOf(element);
break;
}
}
if (idValid && idListPosition != -1) {
System.out.println("Welcome !");
String[] returnValue = {"true", identifications.get(idListPosition), identifications.get(idListPosition + 1), identifications.get(idListPosition + 2)};
return (returnValue);
} else {
System.out.println("Error : the ID you entered does not exist. Please try again");
providedID = null;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
}
}
}
public static void main(String[] args) {
init();
String[] response = signIn();
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
protected static void init() {
identifications.add("056789");
identifications.add("teacher");
identifications.add("Temperson");
}
}
The Teacher and Student classes are empty for now. I just made them use the super constructor of their parent class Person :
public class Person {
String type;
String name;
String idNumber;
public Person(String idnumber, String newType, String providedName) {
this.idNumber = idnumber;
this.type = newType;
this.name = providedName;
}
protected String[] showInfos() {
String[] returnValue = {this.type, this.name, this.idNumber};
return returnValue;
}
}
But I get user cannot be resolved to a variable and user cannot be resolved error.
Normally the code that needs user will never run unless sign in has completed. And since sign in never ends before a correct ID is entered, the user variable will always be assigned to a a value.
Thanks for helping !
The scope of the user object is limited to the if condition, hence you are getting this error.
If Teacher and Student extends Person then you can try this piece of code:
public static void main(String[] args) {
init();
String[] response = signIn();
Person user = null;
if (response[2].equals("teacher")) {
user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
You're having a Scope problem here:
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
Variables declared in a if block are local to that if block. You can see this in it's simplest form with an example like this:
if(true) {
String value = "Out of Scope";
}
System.out.println(value); //value cannot be seen outside the if block
You will need to declare your Teacher and/or Student variable outside the if block if you wish to use them after the block (this is where using your inheritance class would come in handy). Using the previous example:
boolean someCondition = true;
String value;
if(someCondition) {
value = "In Scope - True";
} else {
value = "In Scope - False";
}
System.out.println(value); //value can now be seen
You have declared 2 different versions of user, so the print statement can't know which you mean. Or it couldn't if it could see either, but since each is declared inside of its own block, the print doesn't see either of them.
My file works the way I want, except for one issue. After it runs prompt_log_out(), if I type n for no, my code does a System.out.print() of my get_temporary_user_credentials(). So the output looks like this:
Username: griffin.keyes
Password: alphabet soup
Hello, Zookeeper!
As zookeeper, you have access to all of the animals' information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.
Would you like to log out? Please type "y" for Yes or "n" for No.
n
Username: Password: <---This is what I don't understand
Username: griffin.keyes
Password: alphabet soup
...
My desired output is the two lines below it that prompt for a username and password again. I feel like it may have something to do with my while(!logout) { statement, but I can't really think of why this might be the issue.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;
public class Authentication{
public static User temporary_user = new User();
public static File admin_file = new File("admin.txt");
public static File veterinarian_file = new File("veterinarian.txt");
public static File zookeeper_file = new File("zookeeper.txt");
public static int attempt_counter = 0;
public static boolean successful_login = false;
public static Scanner user_input = new Scanner(System.in);
public static boolean log_out = false;
public static void main(String []args) throws Exception{
while (!log_out) {
start_login();
if (successful_login) {
prompt_log_out();
}
}
}
public static void start_login() throws Exception {
User[] all_users = create_users();
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
get_temporary_user_credentials(user_input);
for (User u : all_users) {
if (temporary_user.username.equals(u.username)) {
if (temporary_user.encrypted_password.equals(u.encrypted_password)) {
print_file(u.role);
successful_login = true;
break;
}
}
}
attempt_counter++;
}
if (attempt_counter == 3 && !successful_login) {
//user_input.close();
log_out = true;
System.out.println(); //prints out a blank line for easier readability
System.out.println("You have made too many unsuccessful attempts. The program will now exit.");
}
}
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
}
public static void get_temporary_user_credentials(Scanner user_input) throws Exception{
System.out.print("Username: ");
temporary_user.username = user_input.nextLine();
System.out.print("Password: ");
temporary_user.encrypted_password = encrypt(user_input.nextLine());
}
public static void check_credentials() {
}
public static String encrypt(String original) throws Exception {
StringBuffer sb = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
public static User[] create_users() throws Exception{
User users[] = new User[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
Scanner file_reader = new Scanner(credentials_file);
while (file_reader.hasNextLine()) {
users[index_counter] = new User();
users[index_counter].username = file_reader.findInLine(pattern);
users[index_counter].encrypted_password = file_reader.findInLine(pattern);
users[index_counter].password = file_reader.findInLine(pattern);
users[index_counter].role = file_reader.findInLine(pattern);
if (file_reader.hasNextLine() == true) {
file_reader.nextLine();
}
index_counter++;
}
//file_reader.close();
return users;
}
public static void print_file(String role) throws Exception {
System.out.println(); //prints a blank line for easier readability.
if (role.equals("admin")) {
Scanner file_reader = new Scanner(admin_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else if (role.equals("veterinarian")) {
Scanner file_reader = new Scanner(veterinarian_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else {
Scanner file_reader = new Scanner(zookeeper_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
}
}
class User {
String username;
String password;
String encrypted_password;
String role;
}
Any help would be greatly appreciated.
You have this method using the same Scanner Object "user_input", by call next(). The linebreak is still in the scanner buffer. Then the while loop back to start_login() if 'n' is enter. The linebreak is then consumed by temporary_user.username = user_input.nextLine();
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
// A quick and dirty fix
user_input.nextLine()
}
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
Check the above condition its always true based on your declarations
Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}
import java.util.*;
import java.util.Stack;
class Person {
private String name;
private String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
hire.push(app.dequeue());
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException{
Scanner keyboard = new Scanner (System.in);
Manager user = new Manager();
boolean test = true;
while (test){
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\t2 Hire \n\t3 Fire \n\t4 Quit:");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1){
user.Apply();
}else if (action == 2){
user.hire();
}else if (action == 3){
user.fire();
} else if (action == 4){
System.exit(0);
}
else{
System.out.println("Please try again.");
}
}
}
}
I can't figure out how I can print out the name and ssn of the person I just hired or fired. I tried using peek, but it's not working. Basically, the whole program is about whether to accept and application, hire or fire. If I accept an application, it will prompt for the user to enter their name and ss, and if I press hire/fire it should print out the name and ss of that person.
Youre defining the queue wrong.
Its more like: Queue<Person> app = new LinkedList<Person>();
and you need a print method. Here's the Manager class. The print is called in the the Management Class, and if you define Manager user = new Manager(); you're surly going to be looked at funny.
Remove all the Throws. They are not defined and are not used....
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class Manager
{
Scanner keyboard = new Scanner(System.in);
//private Stack<Person> app = new Stack<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
Queue<Person> app = new LinkedList<Person>();
public void Apply()
{
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
//app.enqueue(apply);
app.add(apply);
}
public void hire()
{
if (!app.isEmpty())
{
hire.push(app.remove());
}
else
{
System.out.println("Nobody to hire.");
}
}
public void fire()
{
if (!hire.isEmpty())
{
fire.push(hire.pop());
}
else
{
System.out.println("Nobody to fire");
}
}
public void dump()
{
while(!app.isEmpty())
{
Person p = app.remove();
System.out.println(p.getName()+" "+ p.getSS());
}
}
}