I was given a class DrivingTestM.java to test with a 2 classes I wrote. Here are the classes I wrote. When i run the DrivingTestM.java it gives me an error with the line:
System.out.println( question.getDescription() );
Im not sure what the error may be. Can anyone try and shed some light on this error? Thanks!
Question.java:
public class Question {
String description;
String answerA;
String answerB;
String answerC;
int correctAnswer;
int answer;
Boolean answerCorrect;
public Question(){
}
public Question(String description, String answerA, String answerB, String answerC, int correctAnswer, int answer){
this.description = description;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.correctAnswer = correctAnswer;
this.answer = answer;
}
public Question(String description, String answerA, String answerB, String answerC, int correctAnswer){
this.description = description;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.correctAnswer = correctAnswer;
}
public Boolean isAnswerCorrect() {
return answerCorrect;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAnswerA() {
return answerA;
}
public void setAnswerA(String answerA) {
this.answerA = answerA;
}
public String getAnswerB() {
return answerB;
}
public void setAnswerB(String answerB) {
this.answerB = answerB;
}
public String getAnswerC() {
return answerC;
}
public void setAnswerC(String answerC) {
this.answerC = answerC;
}
public int getCorrectAnswer() {
return correctAnswer;
}
public void setCorrectAnswer(int correctAnswer) {
this.correctAnswer = correctAnswer;
}
public int getAnswer() {
return answer;
}
public void setAnswer(int answer) {
this.answer = answer;
}
}
DrivingTest.java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DrivingTest {
int currentQuestionIndex = 0;
Question currentQuestion;
Boolean lastQuestion;
int score;
List<Question> q = new ArrayList<Question>();
Question quest = new Question();
public DrivingTest() throws FileNotFoundException{
File f = new File("DrivingTest.txt");
//int n = 1;
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String desc = sc.nextLine();
String A = sc.nextLine();
String B = sc.nextLine();
String C = sc.nextLine();
String h = sc.nextLine();
int a = Integer.parseInt(h);
String blank = sc.nextLine();
q.add(new Question(desc, A,B,C,a) );
}
sc.close();
}
public void setCurrentQuestionIndex(int currentQuestionIndex) {
this.currentQuestionIndex = currentQuestionIndex;
}
public int getCurrentQuestionIndex() {
return currentQuestionIndex;
}
public Boolean isLastQuestion() {
if(currentQuestionIndex == q.size() - 1){
return true;
}
else{
return false;
}
}
public Question getCurrentQuestion() {
return currentQuestion;
}
public void setCurrentQuestion(Question currentQuestion) {
this.currentQuestion = currentQuestion;
}
public int getScore() {
return score;
}
}
DrivingTestM.java (the test file):
import java.io.FileNotFoundException;
public class DrivingTestMain {
public static void main( String args[] ) throws FileNotFoundException
{
DrivingTest drivingTest = new DrivingTest();
while( true )
{
// display the current question
Question question = drivingTest.getCurrentQuestion();
System.out.println( question.getDescription() );
System.out.println( "\t" + question.getAnswerA() );
System.out.println( "\t" + question.getAnswerB() );
System.out.println( "\t" + question.getAnswerC() + "\n" );
// set the answer to the current question to 1
drivingTest.getCurrentQuestion().setAnswer( 1 );
// if this is the last question, we are done.
if( drivingTest.isLastQuestion() ) break;
// it is not the last question, so increment CurrentQuestionIndex
int currentQuestionIndex = drivingTest.getCurrentQuestionIndex();
drivingTest.setCurrentQuestionIndex( currentQuestionIndex + 1 );
}
// display the test score
System.out.println( "Your test score is: " + drivingTest.getScore() );
}
}
you're not setting the current question anywhere before you are trying to use it.
you need a method like:
public void startTest()
{
currentQuestion = q.get(0);
}
and then:
DrivingTest drivingTest = new DrivingTest();
drivingTest.startTest();
while( true )
{
//....
also ensure you have questions to get, or you will get other errors as well..
if you are using eclipse, try Debugging your code by stepping through it...
you might want to look in a better way to terminate that loop as well, currently it will fail at the end of the test...
EDIT: ok the loop wont break, but its really messy...
Edit of the DrivingTest constructor:
public DrivingTest() throws FileNotFoundException{
File f = new File("DrivingTest.txt");
//int n = 1;
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String desc = sc.nextLine();
String A = sc.nextLine();
String B = sc.nextLine();
String C = sc.nextLine();
String h = sc.nextLine();
int a = Integer.parseInt(h);
String blank = sc.nextLine();
q.add(new Question(desc, A,B,C,a) );
}
sc.close();
//ensure it's 0.
currentQuestionIndex = 0;
//sets up your first question object.
setCurrentQuestion( q.get(currentQuestionIndex) );
}
You will get java.lang.NullPointerException because you store your Question object in Q list but you don't read objects from it. Try something like this in main class instead of:
Question question = drivingTest.getCurrentQuestion();
use
List<Question> qList = drivingTest.getQ();
Question question = qList.get(i);
also add Q getter in your DrivingTest class.
If you don't want modify main class than make changes in getCurrentQuestion() method:
int i = 0;
public Question getCurrentQuestion() {
if (i<q.size()-1)
return q.get(i++);
else return q.get(i);
}
.
Related
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
import entidades.*;
public class Main {
public static void main(String[] args) {
Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop == true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.nextLine();
String categoriaPro = sc.nextLine();
prof.NomeVerificacao(profissional, nomePro, categoriaPro);
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissional) {
System.out.println(pro);
This is my Main, it's running fine but i don´t think it is adding the atributes to the list and not verifying either.
i want to add the atributes to a list so i can create different objets but they can not have at least the name equal.
public class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
public void NomeVerificacao(List<Profissional> profissional ,String nome, String categoria) {
if(profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
}else {
for(Profissional pro : profissional) {
if(pro.nome.contentEquals(nome)) {
System.out.println("Já Exite esse nome");
}else {
profissional.add(new Profissional(nome, categoria));
}
}
}
}
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
this is the Profissional Class.
I'm almost there i think but the output keeps saying that the name exists even though it is the first name i'm inserting.
I ran your code on my machine and made 3 changes into it, and it's working for me now,
1)
String nomePro = sc.next();
String categoriaPro = sc.next();
2) In professional class just changed this function a bit:
public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
if (profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
} else {
int i = 0;
for (; i < profissional.size(); i++) {
if (profissional.get(i).nome.equals(nome)) {
System.out.println("Já Exite esse nome");
break;
}
}
if (i == profissional.size()) {
profissional.add(new Profissional(nome, categoria));
}
}
}
3) At the end of the class Main, wrote sc.close(); to close the scanner.
i/p and o/p :
1) RP
red
color
2) RP
orange
color
3) RP
orange
paint
Já Exite esse nome
4) SAIR
nome=red, categoria=color
nome=orange, categoria=color
As you can see in above i/p and o/p, nome=red and nome=orange with categoria=color are added in the list but when we tried to add the same nome=orange again but with different category as paint it didn't add it and printed the message "Já Exite esse nome".
and after entering SAIR, the toString(); printed the list content at the end. So the message will be printed only if we try to add the object with the same name again int list (not the first or any other times).
Further optimizations are possible but for now, it will work!
I can propose the following solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Set is a data structure that makes sure you don't have a duplicated elements
// in this case we use TreeSet structure that accepts comparator which tells that
// we need to compare elements only by professional's name
Set<Profissional> profissionals = new TreeSet<>(Comparator.comparing(Profissional::getNome));
while (true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.next();
String categoriaPro = sc.next();
// add function returns true in case the element we're going to add
// was not presented in Set structure yet. False otherwise.
boolean isNew = profissionals.add(new Profissional(nomePro, categoriaPro));
if (!isNew) {
System.out.println("Professional with name " + nomePro + " already exists");
} else {
System.out.println("Professional with name " + nomePro + " was added");
}
} else if (comando.contentEquals("SAIR")) {
break;
}
}
// just prints all professionals at the end of the program
profissionals.forEach(System.out::println);
}
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
// getters and setters
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
The output will be the following:
RP
test test
Professional with name test was added
RP
test1 test1
Professional with name test1 was added
RP
test test3
Professional with name test already exists
SAIR
nome=test, categoria=test
nome=test1, categoria=test1
package javaapplication8;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JavaApplication8 {
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
}
public static void main(String[] args) {
try {
List<Profissional> profissionalList= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\r\nEnter comando:");
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
System.out.print("nome: ");
String nome = sc.next();
sc.nextLine(); // wait enter
System.out.print("categoria: ");
String categoria = sc.next();
sc.nextLine(); // wait enter
// access constructor of Profissional
Constructor profCtor = Profissional.class.getConstructor(String.class, String.class);
profCtor.setAccessible(true);
// create instance of Profissional
Profissional newItem = (Profissional) profCtor.newInstance(nome, categoria);
// avoid duplicate nome in profissionalList
boolean isExist = false;
for(Profissional pro : profissionalList) {
if(pro != null){
if(pro.nome.toLowerCase().equals(newItem.nome.toLowerCase())){
isExist = true;
break;
}
}
}
if(!isExist){
profissionalList.add(newItem );
}
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissionalList) {
if(pro != null) {
System.out.println("nome: " + pro.nome + " categoria: " + pro.categoria);
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
I'm not sure y this coding is not receiving the input for the adjust variable and gets terminated before it runs completely
public class Question {
int id;
String name;
String type;
double amt;
public Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
public static void main(String[] args)
{ }
}
import java.util.*;
public class Answer {
public static void gettype(Question[] q,String adjust)
{
for(int i=0;i<2;i++)
{
if(q[i].getType()==adjust)
{
System.out.println(q[i].getId());
}
}}
public static void main(String[] args) {
int id;
String name,type,adjust;
double amt;
Scanner s=new Scanner(System.in);
Answer a=new Answer();
System.out.println("enter 2 car inputs");
Question[] q=new Question[2];
for(int i=0;i<2;i++)
{
id=s.nextInt();
s.nextLine();
name=s.nextLine();
type=s.nextLine();
amt=s.nextDouble();
q[i]= new Question(id,name,type,amt);
}
adjust=s.nextLine();
a.gettype(q,adjust);
}
}
While running the code i am able to get the inputs for the car object array.But after that i am not able to get the values for the variable adjust.
So please need help with this one.
I have tried simply to print the objects at the constructor side.
But not able to receive the 9th input which will be assigned to the var adjust
I think this is better. You should understand why mine works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Question {
private int id;
private String name;
private String type;
private double amt;
Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
int getId() {
return id;
}
String getName() {
return name;
}
String getType() {
return type;
}
double getAmt() {
return amt;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Question{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", amt=").append(amt);
sb.append('}');
return sb.toString();
}
}
class Answer {
public static final int NUM_QUESTIONS = 2;
public static void main(String[] args) {
int numQuestions = (args.length > 0) ? Integer.valueOf(args[0]) : NUM_QUESTIONS;
List<Question> questions = new ArrayList<>();
Scanner s = new Scanner(System.in);
for (int i = 0; i < numQuestions; ++i) {
System.out.println(String.format("Question %d", i));
System.out.print("id: ");
int id = s.nextInt();
System.out.print("name: ");
String name = s.next();
System.out.print("type: ");
String type = s.next();
System.out.print("amt: ");
double amt = s.nextDouble();
questions.add(new Question(id, name, type, amt));
}
System.out.println(questions);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Changed my code since I should protect my code from students against plagiarism.
I got this error when I tried to compile my code:
Unresolved compilation problem:
Type mismatch: cannot convert from Object to Entry
at SchoolManager.listGrade(SchoolManager.java:49)
at SchoolManager.main(SchoolManager.java:30)
mainClass.java
public class mainClass {
static Scanner scanner = new Scanner(System.in);
static ArrayList<C> c = new ArrayList();
static ArrayList<Object> ob = new ArrayList();
public static void main(String [] args){
while(true){
System.out.println("----------------------------------------------------------------------------");
System.out.println("New:1 Add:2 ListC:3 ListOb:4 AddE:5 ListE:6");
System.out.println("----------------------------------------------------------------------------");
System.out.print(">> ");
String option = scanner.nextLine();
if(option.equals("0")){
System.out.println(c.size()+" "+ob.size()+" ");
System.out.println("Bye");
break;
}else if(option.equals("1")){
c.add(createC());
}else if(option.equals("2")){
ob.add(createOb());
}else if(option.equals("3")){
listC();
}else if(option.equals("4")){
listOb();
}else if(option.equals("5")){
addE();
}else if(option.equals("6")){
listE();
}else{
System.out.println(" ");
}
}
}
private static void listE() {
System.out.print("");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println(" ");
}else{
System.out.println(" ");
System.out.println(ob);
System.out.println(" ");
for(int i=0;i<ob.getE().size();i++){ // this part is a problem.
Entry e = ob.getE().get(i); // this part is a problem.
System.out.println(e.getC()+"\t"+ge.getT()+"\t"+ge.getE());
}
}
}
private static void addE() {
System.out.print(" ");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println("Could not be found...");
}else{
addE(ob);
}
}
private static Object findOb(String ob1) {
for(int i=0;i<ob.size();i++){
if(ob.get(i).getID().equals(ob1)){
return ob.get(i);
}
}
return null;
}
private static void addE(Object ob) {
System.out.print("? ");
String c_id = scanner.nextLine();
C c = findC(c_id);
if(c==null){
System.out.println("Could not be found...");
}else{
System.out.print("T? ");
String t = scanner.nextLine();
System.out.print("E? ");
String ee = scanner.nextLine();
ob.AddE(new Entry(c,t,ee));
}
}
private static C findC(String c_id) {
for(int i=0;i<c.size();i++){
if(c.get(i).getID().equals(c_id)) return c.get(i);
}
return null;
}
private static void listOb() {
for(int i=0;i<ob.size();i++){
System.out.println(ob.get(i));
}
System.out.println();
}
private static void listC() {
for(int i=0;i<c.size();i++){
System.out.println(c.get(i));
}
System.out.println();
}
private static Object createObject() {
System.out.print("S? ");
String id = scanner.nextLine();
System.out.print("N? ");
String n = scanner.nextLine();
System.out.print("S? ");
String s = scanner.nextLine();
return new Student(id,n,s);
}
private static C createC() {
System.out.print("C? ");
String id = scanner.nextLine();
System.out.print("Ct? ");
String Ct = scanner.nextLine();
return new Course(id,Ct);
}
}
Object.java:
public class Object {
public String ID;
public String n;
public String s;
public ArrayList<C> c;
public ArrayList<Ob> s;
public ArrayList<Entry> e;
public Object() {
}
public Object(String id, String n, String s) {
this.ID = id;
this.n = n;
this.s = s;
c= new ArrayList<C>();
ob= new ArrayList<Ob>();
e= new ArrayList<Entry>();
}
public String getId() {
return ID;
}
public String getN() {
return n;
}
public String getS() {
return s;
}
public String getID() {
return getId();
}
public void AddE(Entry e) {
e.add(Entry); //this part is a problem.
}
public ArrayList<Object> getE() {
return ob; //this part is a problem.
}
public String toString() {
String result = ID + " " + n + " " + s;
for(int i=0; i < c.size(); i++) {
result += c.get(i).toString();
result += "\n";
}
return result;
}
}
C.java:
import java.util.ArrayList;
public class C {
String co;
String t1;
public ArrayList<Ob> ob;
public C(String id, String t1) {
co = id;
this.t1 = t1;
ob = new ArrayList<Object>();
}
public String getCo() {
return co;
}
public String getT1() {
return t1;
}
public String getID() {
return getCo();
}
public String toString() {
String result = co + " " + t1;
for(int i=0; i < ob.size(); i++) {
result += ob.get(i).toString();
result += "\n";
}
return result;
}
}
Entry.java:
public class Entry {
public C c;
public String t;
public String g;
public ArrayList<Ob> g;
public Entry(C c, String term, String gr) {
c=c;
t=t;
gr=gr;
g = new ArrayList<Ob>();
}
public Course getC() {
return c;
}
public String getE() {
return g;
}
public String getT() {
return t;
}
public String toString() {
String result = c+ " " + t+ " " + g;
for(int i=0; i < gr.size(); i++) {
result += gr.get(i).toString();
result += "\n";
}
return result;
}
}
How can I solve this error?
This is the error it is talking about:
GradeEntry ge = student.getGrades().get(i);
Says can't convert from Student to GradeEntry, so I suspected getGrades was actually returning Students and yes that is the case:
public ArrayList<Student> getGrades() {
return students; //this part is a problem.
}
I think you meant to return grades:
public ArrayList<Grade> getGrades() {
return gr;
}