Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to display all items in a stack but it doesn't work.
Here is my Classes:
public class CommandFactory
{
public Command getCommand(String type)
{
if(type.equalsIgnoreCase("c"))
{
return new CreateDVD();
}
//......Other commands
}
return null;
}
public interface DVD
{
int getDvdID();
String getTitle();
int getLength();
int getNumAvailable();
void setNumAvailable(int numAvailable);
String toString();
}
public class Movie implements DVD
{
private int dvdID;
private String title;
private int length;
private int numAvailable;
private String director;
public Movie(int dvdID, String title, int length, int numAvailable, String director)
{
//Constructor
}
public int getDvdID() { return dvdID; }
//...getters and setters
public String toString()
{
return String.format("DVD Information\nID: %d\nTitle: %s\nLength: %d mins\nNumber of available copies: %d\nDirector: %s", dvdID, title, length, numAvailable, director);
}
}
public class CreateDVD implements Command
{
public Stack<DVD> dvdStack = new Stack<>();
private Stack<DVD> dvdUndoStack = new Stack<>();
private DVD dvd;
private DVDFactory dvdFactory = new DVDFactory();
private Scanner kb = new Scanner(System.in);
public void execute()
{
System.out.println("Please enter DVD type (mo=movie/mv=MV)");
String type = kb.next();
dvd = dvdFactory.getDVD(type);
dvdStack.push(dvd);
}
//other methods
}
The implementation below will only show the last item in the stack.
public class DVDHandler
{
Stack<Command> unDoCommandStack = new Stack<>();
Stack<Command> reDoCommandStack = new Stack<>();
Stack<DVD> dvdStack = new Stack<>();
CommandFactory commandFactory = new CommandFactory();
boolean exit = false;
public void run()
{
.
.
.
Scanner kb = new Scanner(System.in);
String input = kb.next();
Command command = commandFactory.getCommand(input);
if(command instanceof CreateDVD)
{
command.execute();
dvdStack = ((CreateDVD) command).getDvdStack();
unDoCommandStack.push(command);
}
.
.
.
else if(input.equalsIgnoreCase("s"))
{
System.out.println("Enter ID(enter a to show all): ");
String input1 = kb.next();
if(input1.equalsIgnoreCase("a"))
{
for (DVD dvd:dvdStack)
{
System.out.println(dvd.toString());
}
}
}
}
}
I have tried to print out the dvdStack and there are multiple items there. I don't why it doesn't work.
And then, I implemented it by using ArrayList below:
ArrayList<DVD> dvdArrayList = new ArrayList<>();
.
.
.
if(command instanceof CreateDVD)
{
command.execute();
dvdArrayList.add( (CreateDVD) command.getDvd() )
unDoCommandStack.push(command);
}
.
.
.
System.out.println("Enter ID(enter a to show all): ");
String input1 = kb.next();
if(input1.equalsIgnoreCase("a"))
{
for (DVD dvd:dvdArrayList)
{
System.out.println(dvd.toString());
}
}
This implementation works for displaying all items. However, I have been told to use stack.
Could someone help me to display all items in stack, please?
Every time you enter "c", a new CreateDVD command is created, which has an empty stack.
Then it's executed, which adds a single DVD to its stack.
Then the DVDHandler's stack is replaced by the stack of the CreateDVD command:
dvdStack = ((CreateDVD) command).getDvdStack();
So it's not surprising to only find one DVD in the stack.
Next time, please post more code so we can help with the issue more clearly. However, based on what you have here, a likely solution is using a for loop and the stack.elementAt method. For example:
public static void stackAttack (int inter){
Stack<Integer> stack=new Stack<Integer>();
stack.push(99);
stack.push(88);
stack.push(77);
stack.push(inter);
for(int n=stack.size(); n>0; n--) {
System.out.println(stack.elementAt(n-1));
}
}
public static void main (String[] args) {
stackAttack(69);
}
will print out each element of the stack in LIFO order without shrinking it. Hope this helps, and please include more info next time.
Related
Good day, is there a more efficient way to do this problem with recursion than using a switch statement. In my courses class I have a recursive association of course and a prerequisite then a set the preReqs in the PreReqs class. How can I print out all of preReqs of a class when a user enter a class which has preReqs? Right now I am in the process of using a switch statement and printing each preReq individually but is there a better way to do this still using recursion?
An example out of this: If the user types that course, all of the preReqs will print out too.
ACS-3947 Algorithm Design
prereq: ACS-2947 Data Structures and Algorithms
ACS-2947 Data Structures and Algorithms
prereq: ACS-1904 Programming Fundamentals II
ACS-1904 Programming Fundamentals II
prereq: ACS-1903 Programming Fundamentals I
ACS-1903 Programming Fundamentals I
no prereq
Course class:
import java.util.*;
public class Course
{
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
}
PreReq class:
import java.util.*;
import java.io.*;
public class Prereqs
{
public static void main (String [] args){
Scanner kb = new Scanner (System.in);
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
System.out.println("Enter course number with the format: AAA-999");
String input = kb.next();
validate(input);
}
public static void course(Course nineteen04, Course nineteen03,Course two47, Course three47, Course two09, Course three09, String input ){
Course c1 = nineteen04.getPreReq();
Course c2 = two47.getPreReq();
Course c3 = three47.getPreReq();
Course c4 = two09.getPreReq();
Course c5 = three09.getPreReq();
switch (input){
case "ACS-1904":
System.out.println(nineteen04.getCourseName()+" "+nineteen04.getCourseNumber());
System.out.println("preReq: " + c1.getCourseName()+ " "+ c1.getCourseNumber());
}
}
public static String validate (String input)
{
String arg = input;
boolean valid = arg.length()==7;
if (!valid){
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
valid = arg.charAt(3) == '-';
if(!valid) {
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
for(int i=0; i < 3 && valid; i++){
valid = ((i == 3 && Character.isLetter(arg.charAt(i))));
}
for(int i=3; i < 3 && valid; i++){
valid = ((i==6 && Character.isDigit(arg.charAt(i))));
}
return arg;
}
}
A recursive method needs to contain a condition which terminates the recursion. Your list of courses and their prerequisites remind me of a linked list where each course points to its prerequisite. The list terminates when we reach a course that has no prerequisite. The below code is your Course class with the addition of a main method (imported from your Prereqs class) and the recursive method which I named requirements(). I also added method toString() to make the display of the list of courses and their prerequisites more "human readable". You can experiment by changing the course passed to the initial invocation of method requirements().
public class Course {
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
public String toString() {
return courseNumber + " " + courseName;
}
private static void requirements(Course c) {
if (c == null) {
return;
}
else {
System.out.println(c);
requirements(c.getPreReq());
}
}
public static void main(String[] args) {
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
requirements(three09);
}
}
Running the above code displays the following:
ACS-3909 Advanced Internet Programming
ACS-1903 Programming Fundamentals I
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
In test cases
adding this 3 doctor data into Doctors
Ghouse Cardiology 25, Manzoor Cardiology 15, Sunil Cardiology 15
using
List doctors ......;
doctors.add(new Doctor("Ghouse", "Cardiology", 25) );
after adding remaining both
while running code there is error at some line which I mentioned in code as error generated.
Doctor Class
class Doctor implements Comparable<Doctor> {
private String name;
private String speciality;
private int experience;
Doctor(String name, String speciality, int experience){
this.name=name;
this.speciality=speciality;
this.experience=experience;
}
//getters and setters methods
public int compareTo(Doctor d2) {
//comparing objects for sorting
}
}
Class for get specific doctor data
class DoctorService {
private List<Doctor> doctorsRepository;
public DoctorService(List<Doctor> doctorsRepository) {
this.doctorsRepository = doctorsRepository;
}
public List<Doctor> getExperiencedDoctors(int expr){
List<Doctor> expDoc = new ArrayList<Doctor>();
for (int j=0; j<doctorsRepository.size(); j++){
if (doctorsRepository.get(j).getExp()>=expr){
String strnm = (doctorsRepository.get(j)).getName();
String strspc = (doctorsRepository.get(j)).getSpeciality();
int dxp = (doctorsRepository.get(j)).getExp();
expDoc.add(new Doctor(strnm, strspc, dxp));
}
}
Collections.sort(expDoc);
return expDoc; //THIS LINE GENERATES ERROR
}
public Set<Doctor> getSpecialityDoctor(String spc){
Set<Doctor> spcDoc = new HashSet<Doctor>();
//same for loop as above in list<Doctor>
return spcDoc; //THIS LINE GENERATES ERROR
}
}
Main Class
public class Source {
private static String doctorsData;
static {
StringBuilder doctors = new StringBuilder();
doctors.append("Amy-Pediatrics-16;");
doctors.append("John-Dermatology-10;"
doctorsData = doctors.toString();
}
public static void main(String[] args) {
String[] docStr = doctorsData.split(";");
ArrayList<Doctor> Doctors=new ArrayList<Doctor>();
for(int i=0; i<docStr.length; i++){
String dd= docStr[i];
Doctors.add(new Doctor(docStr[i].split("-")[0], docStr[i].split("-")[1], Integer.parseInt(docStr[i].split("-")[2])));
}
DoctorService ds = new DoctorService(Doctors);
Scanner sc = new Scanner(System.in);
int ch = sc.nextInt();
if(ch==1){
int lmt = sc.nextInt();
List<Doctor> filtDoc=new ArrayList<Doctor>();
filtDoc = ds.getExperiencedDoctors(lmt);
for (int k=0; k<filtDoc.size(); k++){
System.out.println(filtDoc.get(k).getName() + " " +filtDoc.get(k).getSpeciality()+ " " + filtDoc.get(k).getExp() );
}
}else if(ch==2){
//printing from set as above part in if
}else{
System.out.println("Invalid Choice");
}
}
}
You need to override toString() method in your Doctor class:
class Doctor{
...
#Override
public String toString() {
return name+speciality+experience;
}
}
In my main, I am asking the user 2 questions. Both questions have 2 correct answers, which is choice number 2 and 4. Whenever I run the Code and select option 2(for both questions), it results in false. If I run the program and select option 4, it results in true. Both options 2 and 4 are correct. I feel as if the issue is due to my UpdateChoices method(located in MultiCheck class), but I don't know why. I used an ArrayList to save the correct choices, but the first correct choice (option 2) is not saved, resulting in it displaying false. Is there a reason why the first option isn't saved in the ArrayList? My output window is posted below the code.
This is the code I have: Main
package pa4_pandeyay;
import java.util.Scanner;
public class MyQuestionDemo {
public static void main(String[] args) {
// TODO code application logic here
MultiCheck first = new MultiCheck();
first.setText("Which number below is prime?");
first.UpdateChoices("4", false);
first.UpdateChoices("3", true);
first.UpdateChoices("12", false);
first.UpdateChoices("7", true);
first.UpdateChoices("8", false);
MultiCheck second = new MultiCheck();
second.setText("Which number below multiplied equals to 12?");
second.UpdateChoices("4 * 4", false);
second.UpdateChoices("12 * 1", true);
second.UpdateChoices("12 * 2", false);
second.UpdateChoices("-6 * -2", true);
second.UpdateChoices("0 * 12", false);
presentQuestion(first);
presentQuestion(second);
}
public static void presentQuestion(MultiCheck x){
x.display();
System.out.print("Your answer: ");
Scanner sc = new Scanner(System.in);
String response = sc.nextLine();
System.out.println(x.checkAnswer(response));
}
}
Java class Question.java
package pa4_pandeyay;
public class Question {
private String text;
private String answer;
// Create a constructor
public Question(){
text = "";
answer = "";
}
// Set the question text
public void setText(String questionText){
text = questionText;
}
//Set the answer text
public void setAnswer(String correctAnswer){
answer = correctAnswer;
}
// Check the respond with the actual correct answer
public boolean checkAnswer(String response){
return response.equals(answer);
}
public String getText(){
return text; // since variable text it private, we need to create a get method in order to access the private variable
}
// Diplay question to the user:
public void display(){
System.out.println(text);
}
}
Java class MultiCheck:
package pa4_pandeyay;
import java.util.ArrayList;
public class MultiCheck extends Question{
private ArrayList<String> answerChoices;
public MultiCheck(){
super();
answerChoices = new ArrayList<String>();
}
public void UpdateChoices (String choice, boolean correct){ // check the asnwers and save the 'true' answers
answerChoices.add(choice);
if (correct == true)
{
//convert choices.size() to string
String choiceString = "" + answerChoices.size();
setAnswer(choiceString);
}
}
// when calling display, this method will be called.
#Override
public void display(){
System.out.println(getText());
// Display the answer choices
for( int i =0; i< answerChoices.size(); i++){
int choiceNumber = i + 1;
System.out.println(choiceNumber + " : " + answerChoices.get(i));
}
}
The Question class can only store one correct answer by setAnswer(). If you have multiple correct answers, then they will override each other so that only the last one is finally in memory.
This question already has answers here:
Collections.sort with multiple fields
(15 answers)
Closed 7 years ago.
so i'm having issues making this work for me. what this code needs to do is have 3 different (string) fields that then sort them into alphabetical order i've had help before but it wont run on my netbeans. i am currently up to date with all updates as well.
heres the code i have so far
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class test {
private Scanner scan = new Scanner(System.in);
private List<LayoutOfScientist> scientistsNames = new ArrayList<LayoutOfScientist>();
private String name, field, idea;
private boolean continueLoop = true;
private int countTo3 = 0;
private void run() {
while(countTo3<3&&continueLoop) {
if(countTo3>0) {
System.out.println("Would you like to add another scientist? (Y/N)");
}
if(countTo3 == 0 || scan.nextLine().equalsIgnoreCase("y")) {
System.out.println("Please enter the scientist's name:");
name = scan.nextLine();
System.out.println("Please enter the scientist's field:");
field = scan.nextLine();
System.out.println("Please enter the scientist's idea:");
idea = scan.nextLine();
scientistsNames.add(new LayoutOfScientist(name, field, idea));
} else {
continueLoop = false;
}
countTo3++;
}
scientistsNames.sort(Comparator.comparing(LayoutOfScientist::getScientistName));
for(LayoutOfScientist lOS : scientistsNames) {
System.out.println(lOS.getScientistName() + ", " + lOS.getScientistField() + ", " + lOS.getScientistIdea());
}
}
private class LayoutOfScientist {
private String scientistName, scientistField, scientistIdea;
private LayoutOfScientist(String scientistName, String scientistField, String scientistIdea) {
this.scientistName = scientistName;
this.scientistField = scientistField;
this.scientistIdea = scientistIdea;
}
public String getScientistName() {
return scientistName;
}
public String getScientistField() {
return scientistField;
}
public String getScientistIdea() {
return scientistIdea;
}
}
public static void main(String[] args) {
new Test().run();
}
}
Your class name is test (lowercase t) and in your main method, you are calling Test().run().
You need to rename your class to be Test and that should work. Or if your file is test you need to change Test().run() to test().run() instead of public class test to public class test. However, it is good programming practice to name a ClassLikeThis.
If your error is something else entirely, tell us what the error is.
Right now I am working on a programming project in school, I am using Java Eclipse. I am still learning the basics, as I am a Sophomore in high school.
My project relates to the old game called "20 Questions".
My main trouble right now is making the user's answer result with a different question. I have tried and "if else" statement, which took me far, but not far enough. Example:
print ("Is your animal furry?");
if (answer is "True") print("Does this animal wag its tail when excited?")
//This can only be a dog
else print("Is it known to lick itself clean?")
//Else meaning if it doesn't wag its tail, go to cat questions
//only cat in this program
So my predicament is getting the user's answer to change the programs next answer.
Then if the answer they give to the furry animal is false, how do I make it go to the non hairy animal questions?
When you create a Java game, or any Java application with a GUI, using the model / view / controller pattern helps separate your concerns and makes it a lot easier to code.
What you're missing is a model. Here's one way you could model the 20 questions game.
Question.java
Here's a class that holds the question string and two pointers. One pointer for the true answer, and one pointer for the false answer.
package com.ggl.twenty.questions;
public class Question {
private int falseQuestion;
private int trueQuestion;
private String question;
public Question(String question) {
this.question = question;
}
public int getFalseQuestion() {
return falseQuestion;
}
public void setFalseQuestion(int falseQuestion) {
this.falseQuestion = falseQuestion;
}
public int getTrueQuestion() {
return trueQuestion;
}
public void setTrueQuestion(int trueQuestion) {
this.trueQuestion = trueQuestion;
}
public String getQuestion() {
return question;
}
}
TwentyQuestionsModel.java
Next, we create a model class for the game. This class creates and uses a List of questions. From any question, you can get the next question by performing the getTrueQuestion or getFalseQuestion method.
package com.ggl.twenty.questions;
import java.util.ArrayList;
import java.util.List;
public class TwentyQuestionsModel {
private int questionIndex;
private List<Question> questions;
public TwentyQuestionsModel() {
this.questions = new ArrayList<Question>();
this.questionIndex = 0;
loadQuestions();
}
private void loadQuestions() {
Question q0 = new Question("Is it a vegetable?");
this.questions.add(q0);
Question q1 = new Question("Is it a mineral?");
this.questions.add(q1);
Question q2 = new Question("Is it a mammal?");
this.questions.add(q2);
// ...
q0.setFalseQuestion(1);
q0.setTrueQuestion(3);
// ...
}
public String getTrueQuestion() {
Question q = questions.get(questionIndex);
this.questionIndex = q.getTrueQuestion();
return questions.get(questionIndex).getQuestion();
}
public String getFalseQuestion() {
Question q = questions.get(questionIndex);
this.questionIndex = q.getFalseQuestion();
return questions.get(questionIndex).getQuestion();
}
public String getFirstQuestion() {
return questions.get(questionIndex).getQuestion();
}
}
You still have to code a view and a controller. The right model makes it much easier, as you can separate your concerns.
Here my solution just with a question class:
import java.util.Scanner;
public class Question {
private String message = null;
private boolean answered = false;
private Question yes = null;
private Question no = null;
public Question(String message)
{
this.message = message;
}
public void setAnswered(boolean answered)
{
this.answered = answered;
}
public boolean getAnswered()
{
return this.answered;
}
public void setYes(Question yes)
{
this.yes = yes;
}
public void setNo(Question no)
{
this.no = no;
}
public Question getYes()
{
return this.yes;
}
public Question getNo()
{
return this.no;
}
public String getMessage()
{
return this.message;
}
public static void runQuestionnaire(Question startQuestion)
{
String yes = "y";
System.out.println("Some questions. Type 'y' for yes and 'n' for no\nand press enter.");
Scanner sc = new Scanner(System.in);
String answer = null;
Question current = startQuestion;
boolean answered = false;
do
{
System.out.println(current.getMessage());
answer = sc.next();
if(answer.equals(yes))
{
current = current.getYes();
}
else
{
current = current.getNo();
}
answered = current.getAnswered();
}
while(!answered);
System.out.println(current.getMessage());
sc.close();
}
public static void main(String[] args) {
// creating the question tree
Question startQuestion = new Question("Is it fury?");
Question yes1 = new Question("Has it 4 legs?");
Question no1 = new Question("It is a human beeing.");
no1.setAnswered(true);
startQuestion.setYes(yes1);
startQuestion.setNo(no1);
Question yes11 = new Question("Is it blue?");
Question yes111 = new Question("It is a whale.");
yes111.setAnswered(true);
Question no111 = new Question("It is a bear.");
no111.setAnswered(true);
yes1.setYes(yes11);
Question no11 = new Question("It is a bird.");
no11.setAnswered(true);
yes1.setNo(no11);
yes11.setYes(yes111);
yes11.setNo(no111);
Question.runQuestionnaire(startQuestion);
}