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.
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
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.
I am creating a program in Java for a restaurant. I am using ArrayList but for some reason my starter class doesn't seem to run in the main menu.
This is my starter class:
import java.util.ArrayList;
public class Starter
{
Starter()
{
String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
//System.out.println(myList[]);
}
}
This seems to be correct, but when I try to choose from the Main menu it doesn't seem to work.
Main Menu:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a =input.nextInt();
input.nextLine();
if(a==1)
{
System.out.println("Starter");
Starter OS1=new Starter();
System.out.println("Your starter is "+OS1.myList[]);
}
else if(a==2)
{
System.out.println("Main Course");
MaiinCourse OMC1=new MaiinCourse();
System.out.println("Your MainCourse is "+OMC1.MCname);
System.out.println("The price is "+OMC1.MCprice);
}
else if(a==3)
{
System.out.println("Desert");
Deserrt ODS1=new Deserrt();
System.out.println("Your Desert is "+ODS1.DSname);
System.out.println("The price is "+ODS1.DSprice);
}
else
{
System.out.println("End");
System.out.println("Program Closing");
System.exit(1);
}
}
}
The error I get is:
'.class' expected System.out.println("Your starter is "+OS1.myList[]);
How to fix this?
When I run the main menu it should allow me to choose from the array list.
I did few changes to your code. Now it works. Try and see.
import java.util.Arrays;
import java.util.Scanner;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1)
{
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println("Your starter is " + Arrays.toString(OS1.getMyList()));
}
}
}
class Starter
{
private String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
public String[] getMyList()
{
return myList;
}
}
Your code won't work because you are trying to give an Array values within you class constructor (Starter constructor in this case). This will lead to a RunTime exception because you cannot create Array constants within a constructor. I much more viable approach would be to create a private Array as an attribute for each object that you create of type "Starter". Then you can use something that we call a "Getter" method to get the value of the myList attribute for the instance you're creating. Here's a mini example of how we can change your Starter class structure below:
public class Starter {
private String[] myList = {"Coffee", "Tea", "Somola", "Cake"};
public String[] getterMethod() {
return this.myList;
}
}
Now we have what is called a "Getter" method in Java which will return the private class attribute so that users cannot alter the internal state of the Object. Here is an example of how you will call the Array in your main method:
public class App {
public static void main( String[] args ) throws IOException{
System.out.println("1=Starter");
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int a = input.nextInt();
if(a == 1) {
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println(Arrays.toString(OS1.getterMethod()));
}
}
}
That is a very simplified version of your code that I simply used to illustrate the broader concept. Here is the output:
1=Starter
Enter a number
1
Starter
[Coffee, Tea, Somola, Cake]
We simply call the getterMethod() which will return the value for the private Array that you are looking for.
Actually, your myArray is not visible outside the Starter class, so you have to make it visible by declaring as public, or package default. Here you can take help of Arraylist.
So you can change your class as below :
public class Starter {
// this myList will be visible outside of this class and can be accessed to show menu.
ArrayList<String> myList = new ArrayList<>();
Starter() {
String[] myArray = { "Coffee", "Tea", "Somosas", "Cake" };
for (String str : myArray) {
myList.add(str);
}
//System.out.println(myList);
}
}
and kindly update Your Menu.java class as below :
import java.util.Scanner;
public class Menu {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1) {
System.out.println("Starter : ");
Starter os1 = new Starter();
for (String str : os1.myList) {
System.out.print(str + " ");
}
}
}
}
I got a message says error: cannot find symbol regarding on c1.certificateAwarded(grade); statement. I have no idea what is the problem. Really need all the help I can get.
Here's the code:
ExamDetails.java
package Exams;
import javax.swing.JOptionPane;
public class ExamDetails {
public static void main(String[] args) {
StudentResults sr = new StudentResults();
sr.inputStudentName();
sr.inputExamName();
sr.inputScore();
sr.inputGrade();
sr.DisplayDetails();
Certificates c1 = new Certificates();
c1.certificateAwarded(grade);
}
}
StudentResults.java
package Exams;
import javax.swing.JOptionPane;
public class StudentResults {
private String fullname;
private String examName;
private int examScore;
private int examGrade;
public String getStudentName()
{
return fullname;
}
public void setStudentName(String name)
{
fullname = name;
}
public String getExamName()
{
return examName;
}
public void setExamName(String exam)
{
examName = exam;
}
public int getExamScore()
{
return examScore;
}
public void setExamScore(int score)
{
examScore = score;
}
public int getExamGrade()
{
return examGrade;
}
public void setExamGrade(int grade)
{
examGrade = grade;
}
public void inputStudentName()
{
fullname = JOptionPane.showInputDialog("Enter the student's name");
}
public void inputExamName()
{
examName = JOptionPane.showInputDialog("Enter the subject's name");
}
public void inputScore()
{
String scoreString = new String();
JOptionPane.showInputDialog("Enter the student's score");
examScore = Integer.parseInt(scoreString);
}
public void inputGrade()
{
String gradeString = new String();
JOptionPane.showInputDialog("Enter the student's grade");
examGrade = Integer.parseInt(gradeString);
}
public String DisplayDetails()
{
String d;
d = "Student Name : " + fullname + "Exam Name : " + examName + "Score : " + examScore + "Grade : " + examGrade;
return d;
}
}
Certificates.java
package Exams;
public class Certificates extends StudentResults {
private String certificate;
public String Grade;
Certificates()
{
super();
certificate = "No Certificate Awarded";
}
String certificateAwarded(/*int grade*/) {
//StudentResults g = new StudentResults();
//Grade = g.inputGrade();
//Grade = inputGrade(examGrade);
if(Grade.equals("Grade : A"))
{
this.certificate = "Certificate of Excellence";
}
else
if(Grade.equals("Grade : B"))
{
this.certificate = "Certificate of Achievement";
}
else
if(Grade.equals("Grade : C"))
{
this.certificate = "Certificate of Achievement";
}
else
this.certificate = "No Certificate Awardedt";
return this.certificate;
}
}
In the ExamDetails.java class, you don't declare or instantiate the grade variable that you're passing to the certificateAwarded method.
Also, you have parameters commented out in your Certificates.java class. You should uncomment the parameter.
For your code to compile, grade would have to be either
a local variable declared within the main method
a field defined on the ExamDetails class
Neither of these declarations are present so the compiler is telling you that it can't find the grade "symbol".
Try adding int grade = sr.getExamGrade(); above the problem line, or something similar.
As the comment suggested, you need to have "grade" declared. Without it, the compiler can't complete determining what the signature is for Certficates.certificateAwarded, since what goes in the argument list is part of the signature. More importantly, you have this in your code:
String certificateAwarded(/* int grade */)
The parameter, "int grade" is commented out. So the compiler sees this:
String certificateAwarded( )
So, what the compiler might be telling you is that it is looking for a method of Certificates named certificateAwarded that takes 1 argument of type {whatever type "grade" is}. It doesn't find that.
I said "might be" because you are missing two symbols on the line in question: grade and a method with a matching signature.
I can think of two things you can try to fix it:
Change " c1.certificateAwarded(grade);" to "c1.certificateAwarded();"
Declare "grade" to be an int somewhere in main (or in a place that is visible within main) and change "String certificateAwarded(/int grade/)" to "String certificateAwarded(int grade)".
I would start by trying the first option. If it is necessary to try the second, you will need to add additional code in both main (or place where grade is visible to main) and in the certificateAwarded method.
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);
}