I'm working on a project where I have to test to make sure certain code will meet user expectations. The only part I was supposed to do is write the code for GetCourseByCourseID. Everything else was given to me. I've written the code and run the program. The program runs, but it doesn't display anything. What do I need to do?
public class Course {
public Course(String id, String title, int creditHours, String description, String prerequisiteCourse)
{
this.CourseID = id;
this.CourseTitle = title;
this.CreditHours = creditHours;
this.Description = description;
this.PrerequisiteCourse = prerequisiteCourse;
}
public String CourseID;
public String CourseTitle;
public int CreditHours;
public String Description;
public String PrerequisiteCourse;
}
public class CourseList {
public Course[] CourseArray =
{
new Course ("CIS 400", "OO Analysis & Design", 4, "Important class", "CIS 110") ,
new Course ("CIS 150A" , "VB.NET Programming", 4, "Good Introduction to programming", "CIS 100") ,
new Course ("CIS 150B", "C# Programming with labs", 4, "Follow-up to CIS 100", "CIS 100")
};
public Course GetCourseByCourseID(String id)
{
for (Course course : CourseArray)
if (course.CourseID == id)
return course;
return null;
}
}
public class CourseListTest {
public static void main(String[] args)
{
GetCourseByCourseIDTestWhenCourseExists();
GetCourseByCourseIDTestWhenCourseDoesNotExist();
}
public static void GetCourseByCourseIDTestWhenCourseExists()
{
CourseList myCourseList = new CourseList();
Course myCourse = myCourseList.GetCourseByCourseID("CIS 400");
if (myCourse.CourseID != "CIS 400")
System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseExists(): Returned CourseID Not equal (CIS 400)");
}
public static void GetCourseByCourseIDTestWhenCourseDoesNotExist()
{
CourseList myCourseList = new CourseList();
Course myCourse = myCourseList.GetCourseByCourseID("CIS 101");
if (myCourse != null)
System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseDoesNotExist(): should have returned null");
}
}
This is for a class. I asked my professor why it wasn't showing up and he said he wasn't familiar with java and that I should use visual basic. I personally hate visual basic (bad experience with it in a prior class) and I would love to know how it works in java! I have looked everywhere for 2 hours and not found anything! Please help!
One of your problems is the line if (course.CourseID == id), which isn't comparing Strings correctly. You need to use equals, not == for String comparison, because == just checks whether two Strings are the actual same object in memory.
if (course.CourseID.equals(id))
This is explained in depth at How do I compare strings in Java?
You have the same problem on the line that says if (myCourse.CourseID != "CIS 400")
Try fixing those, and post a comment if your program still doesn't work.
course.CourseID == id
myCourse.CourseID != "CIS 400"
Change these two lines to:
course.CourseID.equals(id)
!myCourse.CourseID.equals("CIS 400")
See if you can get what you want.
Basically, you want to use String#equals to check for string equality instead of using ==.
public Course GetCourseByCourseID(String id){
for (Course course : CourseArray){
if (course.CourseID.equals(id)){
return course;
}
}
return null;
}
What you were doing was returning null on the first course before you could loop through the others.
Related
//Sorting userDefined object from ArrayList<>...
import java.io.*;
import java.util.*;
class Song implements Comparable<Song>{
String title;
String movie;
String rating;
public int compareTo(Song s){
//System.out.println(getTitle()+" "+s.getTitle());
/*The upper comment is for testing purpose,
*because i wanted to see whats the value getTitle() compares..
*but i couldn't understand.
*/
return getTitle().compareTo(s.getTitle());
}
public Song(String t, String m, String r){
//R.I.P. Naming Convention.
title = t;
movie = m;
rating = r;
}
public String getTitle(){
return title;
}
public String toString(){
return title;
}
}
class ArrayListDemo{
ArrayList<Song> songsList = new ArrayList<Song>();
public static void main(String[] args){
new ArrayListDemo();
}
public ArrayListDemo(){
getSongs();
System.out.println(songsList);
Collections.sort(songsList);
System.out.println(songsList);
}
public void getSongs(){
try{
File file = new File("SongsList.txt");
//check below for SongsList.txt
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null){
addSong(line);
}
} catch(IOException e){
e.printStackTrace();
}
}
public void addSong(String lineToParse){
String[] token = lineToParse.split("/");
Song nextSong = new Song(token[0], token[1], token[2]);
songsList.add(nextSong);
}
}
SongsList.txt
Soch Na Sake / Airlift / 9.1
Jeena / Badlapur / 8.7
Tere Sang Yaara / Rustom / 8.8
Aayat Ki Tarah / BaajiravMastaani / 7.9
Ikk Kudi / UdtaPunjab / 7.5
Tay Hai / Rustom / 7.8
Output:-
Before Sorting...
[Soch Na Sake , Jeena , Tere Sang Yaara , Aayat Ki Tarah , Ikk Kudi , Tay Hai ]
After Sorting...
[Aayat Ki Tarah , Ikk Kudi , Jeena , Soch Na Sake , Tay Hai , Tere Sang Yaara ]
Caution:- Beginner Level English Ahead!!!
So this is working of my program... Reference :-HeadFirstJava 2nd , JukeBox3 Page no.- 550
So, coming to the problem..
i understood most of them...but this is where my mind is rolling.. o.O
public int compareTo(Song s){
return getTitle().compareTo(s.getTitle());
}
getTitle() & s.getTitle()
from where getTitle() gets value and compares it...
ok, i know that compareTo() compares String but and i also know the -1,0,1 (<,=,>) rule,
the thing which cracking me up is from where getTitle() gets the value.
and one more thing... the book says that
Collections.sort(songsList);
when this method gets called, the sort method sends an element from songsList to compareTo() method.. means s.getTitle() = title of the element sent bye sort(). Right ?
but from where the first getTitle() gets the value... the one which is after the return and before the .compareTo().
Kindly assist me here, checked docs, other answers, everything i can in last two days....
in simple words i want to know that from where and which values getTitle() gets to compare.
public int compareTo(Song s) is used to compare 2 Song objects. One of them is the one the method is called on, and the other is passed as an argument.
For example :
Song s1 = ...
Song s2 = ...
int s1.compareTo(s2);
In this example, getTitle() in the body of public int compareTo(Song s) will return the title of s1, while s.getTitle() wil return the title of s2.
Collections.sort(songsList); will always use compareTo to compare 2 Song objects - one of them it will call the method on, and the other will be passed as an argument.
I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);
I am newbie to object orientated programming and trying to construct something which resembles a basic vote counter which should take an int parameter that represents a choice of two candidates and print the election results to the terminal window. albeit (the votes attributable to each candidate and the total votes cast)
The method I am looking for should also return a string that gives information on the success or failure of casting the vote.”your vote has been cast” “invalid choice, no vote cast"
I have created a class and the constructors and also implemented some basic get methods.
I am wondering how I should go about achieving this objective albeit through a conditional statement or using some sort of advanced method.
any help in terms of the syntax or wider approach would be appreciated.
public class VoteCounter {
private String candidate1;
private String candidate2;
private int candidate1Votes;
private int candidate2Votes;
private boolean completed;
public VoteCounter(String candidate1, String candidate2) {
this.candidate1 = candidate1;
this.candidate2 = candidate2;
this.candidate1Votes = 0;
this.candidate2Votes = 0;
this.completed = false;
}
public VoteCounter() {
this("CANDIDATE 1", "CANDIDATE 2");
}
public String getCandidate1 () {
return this.candidate1;
}
public String getCandidate2 () {
return this.candidate2;
}
public Boolean getCompleted () {
return this.completed;
}
public void setCompleted (boolean completed) {
this.completed = completed;
}
}
Something like this?
private String vote(int choice)
{
if(choice == 1)
{
candidate1Votes++;
}
else if(choice == 2)
{
candidate2Votes++;
}
else
{
return "invalid choice, no vote cast";
}
return "your vote has been cast";
}
I would do that in more general manner, avoiding code duplication and allowing to change number of candidates easily.
So let's make a class Vote similar to your VoteCounter but only for one candidate, with following fields:
private String candidate; // init this in constructor
private int candidateVotes; // initially 0, so no need to init
and with vote() method like in other answer but also without a candiadate, so:
public void vote() {
candidateVotes++;
}
Then you can make class VoteCounter which will take any number of candidates and will keep them in Array or Map.
Map<Integer, Vote> votes = new HashMap<>();
then you're creating vote method with choice:
public void vote(int choice) {
votes.get(choice).vote();
}
Then all is left is to iterate through your votes map and find the one with biggest number of votes.
I'm a total newbie to Java, and until now all I've done was draw some shapes and flags. I'm struggling to understand the code I've been given. I need to access values stored in an ArrayList within another class. I'm not sure I'm making any sense, so here are the two classes Seat and Mandate:
package wtf2;
import java.util.*;
public class Seat {
public int index;
public String place;
public int electorate;
public String mp;
public String party;
public String prev;
public ArrayList<Mandate> results;
public Seat(int index, String place) {
this.place = place.trim();
this.index = index;
this.results = new ArrayList<Mandate>();
}
public void addMandate(Mandate m) {
//First candidate is always the MP
if (mp == null) {
mp = m.candidate;
party = m.party;
}
results.add(m);
}
public String toString() {
return "[" + this.index + "," + this.place + "]";
}
}
class Mandate {
public String candidate;
public String party;
public int vote;
public Mandate(String candidate, String party, int vote) {
this.candidate = candidate;
this.party = party;
this.vote = vote;
}
}
The main class contains code that feeds data from 2 text files into Seat and Mandate. From there I managed to access the date in Seat. Like here:
//Who is the MP for "Edinburgh South"
public static String qA(List<Seat> uk) {
for (Seat s : uk)
if (s.place.startsWith("Edinburgh South"))
return (s.mp);
return "Not found";
}
Now,instead of getting just the mp for Edinburgh South I need to get the vote values, compare them to each other, take the second biggest and display the associate party value.
Would appreciate any help, like how to access data from that Array would help me get started at least.
An element in an ArrayList is accesses by its index.
Seems you can just sort your ArrayList based on the vote values of the objects which are in the list.
For this you may want to look here: Sort ArrayList of custom Objects by property
Of course sorting is maybe too much for your given problem. Alternatively,
you may just iterate through the list and pick the two objects with the highest
votes values as you go.
This is what I have and I'm new to Java:
import java.util.*;
public class WordPairs
{
// ArrayList<String> names = new ArrayList<String>();
// ArrayList<String> meanings = new ArrayList<String>();
//names.add("empty");
//meanings.add("empty");
String searchName;
String searchMeaning;
String names[] = new String[25];
String meanings[] = new String[25];
int Q = 1;
public void setWordAdd(String name,String meaning)
{
names[Q] = name;
meanings[Q] = meaning;
Q = Q++;
}
public void setWordDelete(String name)
{
for(int i=0;i<names.length;i++)
{
String check = names[i];
if(check == name)
{
String meanings = meanings.remove(i);
}
}
}
public void setWordSearch(String name)
{
int a = 1;
for(i=0;i<names.size();i++)
{
string check = names.get(i);
if(check == name)
{
searchName = names.get(i);
searchMeaning = meanings.get(i);
a = 0;
}
}
if(a == 1)
{
searchName = "word can not be found";
searchMeaning = "meaning can not be found";
}
}
public String getSearchName()
{
return searchName;
}
public String getSearchMeaning()
{
return searchMeaning;
}
}
http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
I believe you are a beginner, and by reading your code I assume you are not familiar with built-in collections yet (despite of some shy ArrayList attempt). That's ok, no one is born with that knowledge. Here is some reading for you:
Map interface: http://download.oracle.com/javase/6/docs/api/java/util/Map.html
All of implementations of this interface provide functionality you need, but in different ways. For example, HashMap is useful in most cases, but if you need keys (in your code - "names") sorted, TreeMap would be better. LinkedHashMap "remembers" the order in which keys were inserted, and so on. It's very interesting and informative reading and you definitely should know about maps, because they are among most useful Java classes.
Here is introduction to Java Collections Framework in general:
http://download.oracle.com/javase/tutorial/collections/index.html
Be sure to read it, because collections are irreplacable in even simplest Java applications.
I hope that helps, and good luck!