Java HashMaps why does this return null? - java

I setup a test jar app to run for my other program I have been working on this for hours and i cant find a reason for why it returns null. Thanks for helping!
hashy.java
import java.util.HashMap;
public class hashy {
private static HashMap<String, Integer> targets = new HashMap<String, Integer>();
public static void main(String[] args) {
Hashymashy mash = new Hashymashy();
mash.hashyMash();
String name = "Bobby";
int num = 10;
targets.put(name, num);
if (targets.containsKey(name) == true) {
System.out.println("It contains a key!");
} else {
System.out.println("It does not contain a key!");
}
if (targets.containsValue(num) == true) {
System.out.println("It contains a value");
} else {
System.out.println("It does not contain a value!");
}
}
public HashMap<String,Integer> getTargets(){
return targets;
}
}
Hashymashy.java
public class Hashymashy {
public void hashyMash(){
hashy h = new hashy();
String name = "Bobby";
Integer fnum = h.getTargets().get(name);
System.out.println("Number is "+fnum+"!");
}
}

You are trying to retrieve the value associated with "Bobby" before adding it to the HashMap.
mash.hashyMash();
is called before targets.put(name, num);, so
Integer fnum = h.getTargets().get("Bobby");
will return null since there is no "Bobby" yet.
PS: seems like a bad design to me, since Hashymashy classes create instances of hashy classes & vice-versa.

Related

Recursion in java with objects of courses and prerequisites

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

Trying to find if a java list object has an element STRING or INT?

I am trying to find if a list contains a string. I have a list object as follows:
Please note this is just example code, to illustrate my point/question!
import java.util.List;
public class FilterByList {
private String actionHero;
private String actionHero2;
private String move;
private int number;
private String actionHero3;
public FilterByList(String actionHero, String actionHero2, String move, int number, String actionHero3) {
this.actionHero = actionHero;
this.actionHero2 = actionHero2;
this.move = move;
this.number = number;
this.actionHero3 = actionHero3;
}
public String getActionHero() {
return actionHero;
}
public void setActionHero(String actionHero) {
this.actionHero = actionHero;
}
public String getActionHero2() {
return actionHero2;
}
public void setActionHero2(String actionHero2) {
this.actionHero2 = actionHero2;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getActionHero3() {
return actionHero3;
}
public void setActionHero3(String actionHero3) {
this.actionHero3 = actionHero3;
}
}
And then:
public static void main(String[] args) {
List<FilterByList> myList = Collections.singletonList(
new FilterByList("superman", "antman", "ACTION", 123, "batman"));
System.out.println(myList);
if (myList.contains("batman")) {
System.out.println("found it!");
} else {
System.out.println("************************* Did not find anything!!1");
}
}
It does NOT find batman in the list object. So what is printed is the follows:
[com.company.FilterByList#7577b641]
************************* Did not find anything!!1
Any idea how I can:
a) print the contents of the list?
b) find an element in the list with as little code as possible?
Would appreciate your help. Please use my code context to answer as it will give me more pointers.
You run contains on List<FilterByList> and that list doesn't have String batman
It has instance of FilterByList, that one of members is field of type string and value 'batman'
Based on your code. You create instance of object FilterByList and you try to compare that object with String
Line
if (myList.contains("batman")) {
Those object are different types, that is the reason, why it is not found
To check if there is batman you can use Stream API
boolean d = myList.stream().map(FilterByList::getActionHero3).anyMatch(hero3 -> hero3.equals("batman"));
Add to your FilterByList class containsHero(String hero) where you compare hero with each of 3 heroes. You don't need to store this single object in List. Just use it.
FilterByList f = new FilterByList("superman", "antman", "ACTION", 123, "batman");
if (f.containsHero("batman")) {
System.out.println("found it!");
} else {
System.out.println("************************* Did not find anything!!1");
}
P.S. imho all the things you are trying to do looks very strange...
I added a new method to the class for searching
public boolean containsHero(String hero) {
return actionHero.equals(hero) || actionHero2.equals(hero) || actionHero3.equals(hero);
}
And then used it with streams like this
if (myList.stream().anyMatch(f -> f.containsHero("batman"))) {
System.out.println("found it!");
}
To get a readable output of your class you can override the toString() method, here is one example
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(actionHero);
builder.append(", ");
builder.append(actionHero2);
builder.append(", ");
builder.append(actionHero3);
builder.append(": ");
builder.append(move);
builder.append(": ");
builder.append(number);
return builder.toString();
}
Doing System.out.println(myList);will then output
[superman, antman, batman: ACTION: 123]
You can put into the list two different types of objects, e.g. String and Integer if you will omit the generic type, and implicitly it will be List<Object> myList = new ArrayList<Object>(); for example:
List myList = new ArrayList();
myList.add("superman");
myList.add("antman");
myList.add("ACTION");
myList.add(123);
myList.add("batman");
System.out.println(myList);
if (myList.contains("batman")) {
System.out.println("found it!");
} else {
System.out.println("************************* Did not find anything!!1");
}
But it's not a good way to use collections. For sure, it depends of your particular task, but I'd like to advice to use different collections with different types.
If you want to achieve exactly what you're asking about, you can use Stream API like this:
List<FilterByList> myList = Collections.singletonList(
new FilterByList("superman", "antman", "ACTION", 123, "batman"));
System.out.println(myList);
if (myList.stream().map(FilterByList::getActionHero3).allMatch("batman"::equals)) {
System.out.println("found it!");
} else {
System.out.println("************************* Did not find anything!!1");
}
anyMatch method is more preferable to use, if there will be more than one element in the collection:
(myList.stream().map(FilterByList::getActionHero3).anyMatch("batman"::equals))

arraylist in java to sort data [duplicate]

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.

"error: cannot find symbol" regarding on Inheritance-related program

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.

Debugger stopped on uncompilable source code.

I just learnt how to use Arrays i wrote this program in Java on Netbeans. It compiled with no errors but gave me a blank output my if was true but when it jumped to the else the output was ok
THIS IS MY JAVA CLASS
public class VacationScale {
public int[] vacationDays;
public int yearsOfService;
public void setVacationScale(){
vacationDays = new int[7];
vacationDays[0] = 10;
vacationDays[1] = 15;
vacationDays[2] = 15;
vacationDays[3] = 15;
vacationDays[4] = 20;
vacationDays[5] = 20;
vacationDays[6] = 25;
}
public void displayVacationDays(){
if (yearsOfService >= 0){
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
}else {
System.out.println("invalid number of years");
}
}
}
AND THIS IS MY MAIN CLASS (TESTING)
public class VacationScaleTest {
public static void main(String[] args) {
VacationScale personOne;
personOne = new VacationScale();
personOne.yearsOfService = 2;
personOne.displayVacationDays();
}
}
BOTH IN THE SAME PROJECT
i tried debugging and got Debugger stopped on uncompilable source code at
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
That's because you still haven't set the array vacationDays[] at the point you make the call to displayVacationDays().
Do the following - add this line before the line where you have personOne.displayVacationDays(),
personOne.setVacationScale();
// Now make the call to display vacation days
I got the same error message in a completely different constellation.
I'm using java fx
I googled for it and found no similar cases. After some tests, I found out that when creating a new PropertyValueFactory I got this nerving error message.
The line of code that caused the problem was:
TableColumn<Values, String> col = new TableColumn<>(val.getName());
col.setCellValueFactory(
new PropertyValueFactory<Values,String>("Value")
);
The class Values is a subclass and looks like this:
private class Values {
private final SimpleStringProperty vall;
public Values(String d) {
this.vall = new SimpleStringProperty(d);
}
public String getValue() {
return vall.get();
}
public void setValue(String value) {
vall.set(value);
}
}
Solution:
After a lot of checking, I found out that my Values class must be PUBLIC and not private.
public class Values {
...
}
I hope it can be useful for someone.

Categories

Resources