Treeset of exam printed - java

Hello i've these 3 classes:
Here i put the name of a student and the exams he gave
package traccia50719;
import java.util.*;
public class Lab {
public static void main(String[] args) {
Studente studente = inserimento();
System.out.println("fine inserimento\n");
studente.print();
System.out.println("\nfine programma");
}
private static Studente inserimento() {
Studente s = null;
Esame esame=null;
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
int matricola= mat.nextInt();
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome= cog.next();
System.out.println("\nNome:");
Scanner nom = new Scanner(System.in);
String nome= nom.next();
s= new Studente(matricola, cognome, nome);
do{
System.out.println("\ncodice esame:");
Scanner cod = new Scanner(System.in);
int codicesame= cod.nextInt();
if(codicesame==0){
break;
}
System.out.println("\nNome esame:");
Scanner nomes = new Scanner(System.in);
String nomesame= nomes.next();
System.out.println("\nvoto esame:");
Scanner vot = new Scanner(System.in);
int votoesame= vot.nextInt();
esame = new Esame(codicesame,nomesame,votoesame);
s.addEsame(esame);
}while(true);
return s;
}
}
In this class i've the student with the constructor but when i try to print exams with iterator i have only one exam printed. Why?
package traccia50719;
import java.util.*;
public class Studente {
private int matricola;
private String cognome;
private String nome;
private Set<Esame> esami = new TreeSet<Esame>();
public Studente(int matricola, String cognome, String nome){
this.matricola=matricola;
this.cognome=cognome;
this.nome=nome;
}
public void addEsame(Esame e){
this.esami.add(e);
}
public void print(){
System.out.println("\nmatricola:" + this.matricola);
System.out.println("\ncognome:" + this.cognome);
System.out.println("\nnome:" + this.nome);
Iterator<Esame> i = this.esami.iterator();
while(i.hasNext()){
Esame e = (Esame) i.next();
e.stampaesame();
}
}
}
This is the 3 class Exam and i've stampaEsame() that print name and the result of the exam
package traccia50719;
public class Esame implements Comparable{
private int codice;
private String nome;
private int voto;
public Esame(int codice, String nome, int voto){
this.codice=codice;
this.nome=nome;
this.voto=voto;
}
public void stampaesame(){
System.out.println("\n nome esame:" +this.nome);
System.out.println("\n voto esame:" +this.voto);
}
public boolean equals(Object o) {
Esame esa = (Esame) o;
if(this.codice==esa.codice){
return true;
}else return false;
}
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
}

Replace the line with esami like this.
private List<Esame> esami = new List<Esame>();
If it works like this, then the problem was with the way you override the hashCode() and equals() methods for the Esami class. Due to this TreeSet is treting all of your inserts as being the same element and as a set it can only contain one instance of the same element.
Remeber, hashCode() and equals() must be overridden together ;)

Related

I am not correctly reading from the text file into an ArrayList after parsing each line into an object

I am trying to read from the txt file and then parse through it and make each line a new object in an ArrayList. I keeps telling me its null and I cannot figure out why. I have not used java in a long time so I'm sure its dumb.
public class AccessibilityTest {
private String cat;
private String googErr;
private String waveErr;
private String sortErr;
private String lintErr;
private String desc;
public AccessibilityTest(String cat,String googErr,String waveErr,String sortErr,String lintErr, String desc){
this.cat = cat;
this.googErr = googErr;
this.waveErr = waveErr;
this.sortErr = sortErr;
this.lintErr = lintErr;
this.desc = desc;
}
public static void main(String[] args) {
AccessibilityResults.readTxtFile("a11yCheckersResults.txt");//this is one place im getting the error and its me trying to target that txt file
System.out.println();
}
public String getCategory() {
return cat;
}
public String getGoogleResult() {
return googErr;
}
public String getWaveResult() {
return waveErr;
}
public String getSortsiteResult() {
return sortErr;
}
public String getAslintResult() {
return lintErr;
}
public String getDescription() {
return desc;
}
#Override
public String toString(){
return "fsdfse"+ getCategory() + getGoogleResult()+ getWaveResult()+ getSortsiteResult() + getAslintResult() + getDescription();
}
}
This is the other file where I am actually parsing through the txt file and creating the objects.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class AccessibilityResults {
private static ArrayList<AccessibilityTest> list;
public AccessibilityResults() {
list = new ArrayList<>();
}
public static void readTxtFile(String fileName){
try(Scanner reader = new Scanner(new File(fileName))){
while(reader.hasNextLine()){
String cat = reader.next();
String err1 = reader.next();
String err2 = reader.next();
String err3 = reader.next();
String err4 = reader.next();
String desc = reader.nextLine();
list.add(new AccessibilityTest(cat, err1, err2, err3, err4,desc));//this is one spot im getting the error
}
} catch(FileNotFoundException e){
System.out.println("File not found: " + fileName);
}`enter code here`
}
}
//txt file
//a11yCheckersResults.txt
The reason is that list and readTxtFile is static method,but the readTxtFile() that init list is not static,and in java static properties and method will be inited before none static which cause it
To solve it,there are several options:
one option is just to remove all the static in list and readTxtFile(),another options is just init list when declare it private static ArrayList<AccessibilityTest> list = new ArrayList<>();
// static
private static ArrayList<AccessibilityTest> list;
// no static,so list will always be null
public AccessibilityResults() {
list = new ArrayList<>();
}
// static
public static void readTxtFile(String fileName){
try(Scanner reader = new Scanner(new File(fileName))){
while(reader.hasNextLine()){
String cat = reader.next();
String err1 = reader.next();
String err2 = reader.next();
String err3 = reader.next();
String err4 = reader.next();
String desc = reader.nextLine();
list.add(new AccessibilityTest(cat, err1, err2, err3, err4,desc));//this is one spot im getting the error
}
} catch(FileNotFoundException e){
System.out.println("File not found: " + fileName);
}
}
}

How to insert value from user defined datatypes to object in java?

I'm creating an object of type Lightmode, which is a class.
There's also a Smartlamp class which is having a variable of custom data of type Lighmodes and I want to show my defined data type value over there.
I'm trying to create an object and then insert a string against my Lightmode data type which is showing error. I want to print like this:
Name:  lamp1 
Location: 3.1 
Switched On:  false 
Mode:  STANDARD 
Here mode is lightmode datatype and I'm getting a problem over it.
...
public class LightModes
{
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}...
...package smart.home.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size,mode;
int displayindex=1;
String name;
double location,temperature;
boolean status=false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size=in.nextInt();
// TODO code application logic here
SmartLamp[] smartLamp=new SmartLamp[size];// creating an array object of smartdevice class
//
for(int j=0;j<size;j++)
{
System.out.println("Enter Lamp name.");
name=input.readLine();
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation=new Scanner(System.in);
location=devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode=new Scanner(System.in);
mode=lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus=new Scanner(System.in);
int currentstatus=devicestatus.nextInt();
if(currentstatus==1)
{
status=true;
}
else if(currentstatus==0)
{
status=false;
}
LightModes light = null;
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}...
...public class SmartLamp extends SmartDevice{
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{"+"\nName."+getName()+"\nLocation."
+getLocation() + "\nSwitchedOn."+isSwitchedOn()+
"\nMode=" + getLightModes() + '}';
}
}...
I downloaded your code and added the missing class SmartDevice. Your code contains two compiler errors.
name = input.readLine();
This line throws java.io.IOException which is an unchecked exception and hence must be handled by your code. There are several ways to do this, one of which is to add throws IOException to method main() in class Step5.
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
The first argument to SmartLamp constructor is an instance of class LightModes but you are passing a String. You need to create an instance of LightModes.
Here is your code with my modifications that get rid of the two compiler errors.
(Note: The below code includes my guessed implementation of class SmartDevice.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException { // Change here.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size, mode;
int displayindex = 1;
String name;
double location, temperature;
boolean status = false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size = in.nextInt();
SmartLamp[] smartLamp = new SmartLamp[size];// creating an array object of smartdevice class
for (int j = 0; j < size; j++) {
System.out.println("Enter Lamp name.");
name = input.readLine(); // throws java.io.IOException
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation = new Scanner(System.in);
location = devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode = new Scanner(System.in);
mode = lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus = new Scanner(System.in);
int currentstatus = devicestatus.nextInt();
if (currentstatus == 1) {
status = true;
}
else if (currentstatus == 0) {
status = false;
}
LightModes light = new LightModes(); // Change here.
light.setNIGHT_MODE(light.getNIGHT_MODE()); // Change here.
smartLamp[j] = new SmartLamp(light, name, location, status); // Change here.
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}
class LightModes {
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String name, double location, boolean switchedOn) {
this.name = name;
this.location = location;
this.switchedOn = switchedOn;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean isSwitchedOn() {
return switchedOn;
}
}
class SmartLamp extends SmartDevice {
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{" + "\nName." + getName() + "\nLocation." + getLocation()
+ "\nSwitchedOn." + isSwitchedOn() + "\nMode=" + getLightModes() + '}';
}
}

how to print the default constructor with private variables from another class

I want to print the default private bloodtype and rhfactor which is O+ and + I want to print it from another class which has the main method.
I've already tried creating new objects and printed them but still it says that I'm accessing a private variable. When you input something on the scanner it prints it but if you input none I want to print the constructor with private variables!
public class blooddata {
private String bloodtype;
private String rhFactor;
blooddata(){
bloodtype = "O";
rhFactor = "+";
}
blooddata(String btx, String rhx){
this.bloodtype = btx;
this.rhFactor = rhx;
}
public String getblood (String bloodtype){
return bloodtype;
}
public String getfactor (String rhFactor){
return rhFactor;
}
public void setblood(String bloodtype){
this.bloodtype = bloodtype;
}
public void setfactor(String factor){
this.rhFactor = factor;
}
}
here is the class that has main method
import java.util.Scanner;
public class Runblooddata {
static Scanner sc = new Scanner(System.in);
static String btx;
static String rhx;
public static void main(String[] args) {
System.out.print("Enter blood type: ");
btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
rhx = sc.nextLine();
if (btx.isEmpty() || rhx.isEmpty()){
blooddata asd = new blooddata(); //this is where i am lost
}else{
blooddata bd = new blooddata();
bd.setblood(btx);
bd.setfactor(rhx);
System.out.println(bd.getblood(btx));
System.out.println(bd.getfactor(rhx));
}
}
}
Getters aren't supposed to have parameters.
When you declare a method parameter named the same as a field, the parameter hides the field. You basically return the parameter you take.
6.4.1. Shadowing
A declaration d of a field or formal parameter named n shadows, throughout the scope of d, the declarations of any other variables named n that are in scope at the point where d occurs.
public String getBlood() {
return bloodtype;
}
public String getFactor() {
return rhFactor;
}
I will help you to simplify it a bit.
final class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter blood type: ");
String btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
String rhx = sc.nextLine();
BloodData data = btx.isEmpty() || rhx.isEmpty() ?
new BloodData() :
new BloodData(btx, rhx);
System.out.println(data.getBloodType());
System.out.println(data.getRhFactor());
}
}
final class BloodData {
private final String bloodType;
private final String rhFactor;
BloodData() {
this("O", "+");
}
public BloodData(String bloodType, String rhFactor) {
this.bloodType = bloodType;
this.rhFactor = rhFactor;
}
public String getBloodType() {
return bloodType;
}
public String getRhFactor() {
return rhFactor;
}
}
As Andrew has already explain the design issue what you have in your code, I'll guide you towards the solution what you are seeking for.
blooddata bd = new blooddata();
if (!btx.isEmpty() && !rhx.isEmpty()){
bd.setblood(btx);
bd.setfactor(rhx);
}
System.out.println(bd.getblood());
System.out.println(bd.getfactor());

I called a method but it doesn't print

i'm a beginner, I barely know anything, I tired to do some classes and just mess around with methods, but for some reason the method wont print, also I'm really bad with arrays :(
main class :
public class Employees {
static Employee[] array =new Employee[3];
static int i=0;
public void insertEmployee(){
Scanner keyboard=new Scanner(System.in);
System.out.println("please fill in the information :");
System.out.println("name :");
String Name=keyboard.next();
System.out.println("ID :");
long ID=keyboard.nextLong();
System.out.println("Salary :");
double Salary =keyboard.nextDouble();
Citizen s2 =new Citizen(Name);
Employee E= new Employee(ID,s2,Salary);
array[i]=E;
}
public void main(String[] args) {
Employees m1=new Employees();
for ( i=0; i<3;++i){
Employees c1=new Employees();
c1.insertEmployee();
}
System.out.println("*****");
for (i=0;i<3;++i){
array[i].print();
}
}
}
second class :
public class Employee {
private Citizen employeeInfo =new Citizen();
private long employeeID;
private double employeeSalary;
Employee(long employeeID,Citizen employeeInfo ){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
}
Employee(long employeeID,Citizen employeeInfo, double employeeSalary){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
this.employeeSalary=employeeSalary;
}
void print(){
if (employeeSalary==0){
employeeSalary=-1;
}
System.out.println(employeeID+"-"+employeeInfo.getCitizenName()+"-"+employeeSalary);
}
}
and last one:
public class Citizen {
private String citizenName;
private long citizenID;
public Citizen(){
}
public Citizen(String Name){
this.citizenName=Name;
}
public Citizen(String citizenName,long citizenID){
this.citizenName=citizenName;
this.citizenID=citizenID;
}
public String getCitizenName(){
return citizenName;
}
public long getCitizenID(){
return citizenID;
}
}
thank you :)
It has to be public static void main(String[] args). The static is important

printf statement working for one instance of the same class but not another

this is my first time posting so hopefully all goes well. I am having a problem with the following program.
public class Project3 {
public static String fName = "drum_members.txt";
private static Scanner fin;
private static PrintWriter fout;
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String membershipLength;
Member m_1 = new Member();
Member m_2 = new Member();
Member m_3 = new Member();
Member m_4 = new Member();
try {
fin = new Scanner(new File(fName));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + fName);
System.exit(1);
}// end try
m_1.Member();
m_1.calculateFreeItems();
m_1.printMember();
m_2.Member();
m_2.calculateFreeItems();
m_2.printMember();
m_3.Member();
m_3.calculateFreeItems();
m_3.printMember();
m_4.Member();
m_4.calculateFreeItems();
m_4.printMember();
}
public static class Member{
public int id;
public String name;
public String nickName;
public int monthsMembership;
public String favoriteItem;
public int freeItems;
public void Member()
{
name = fin.next();
nickName = fin.next();
monthsMembership = fin.nextInt();
favoriteItem = fin.next();
fin.nextLine();
}
private int calculateFreeItems()
{
freeItems = monthsMembership/12 +1;
return (freeItems);
}
public void setFavoriteitem()
{
System.out.print("Enter new favorite item: ");
favoriteItem = keyboard.next();
}
private String calculatemembershipLength()
{
if(monthsMembership < 12)
return (monthsMembership + "months,");
else
return (monthsMembership/12 + " years, " + monthsMembership%12 + " months,");
}
public void printMember()
{
String months = this.calculatemembershipLength();
System.out.printf("Member #1 - NAME: %22s, NICKNAME:%22s, MEMBER SINCE: %22s FAVORITE ITEM:%22s, FREE ITEMS PER MONTH: %d\n",
name, nickName, months, favoriteItem, freeItems);
}
}
}
After debugging all I know is that the printf statement doesn't work the THIRD time, it will work the 4th time no problem. Any help would be greatly appreciated, and thanks for your time.

Categories

Resources