I'm currently working on a project for class but struggling with a bit of coding relating to
ArrayLists. It is as yet unfinished code; however, when I'm working on the enrollstudent
method I'm having an issue comparing the length of an ArrayList to the variable amountstudents.
Below is a copy of the code for the full class. There is another seperate class related but I don't think it's relevant here.
Any help would be greatly appreciated.
import java.util.*;
import java.util.Scanner;
public class Course {
int amountstudents;
String coursename;
String level;
ArrayList<String> students = new ArrayList<String>();
String tutor;
Scanner in = new Scanner(System.in);
public Course(int MaxCapacity) {
MaxCapacity = amountstudents;
tutor = "Not set yet";
coursename = "Not set yet";
level = "Not set yet";
}
public void enrollstudent(String addstudent) {
if(students.size > amountstudents) {
System.out.println("Unfortunately the class is already full so you can not be enrolled at this time");
}
else {
students.add(Student.fname);
}
}
public void courselevel() {
System.out.println("Please enter course level");
level=in.next();
}
public void coursetitle() {
}
}
It's students.size(), not students.size.
Also, there's another error:
It should be students.add(addstudent), not students.add(Student.fname).
It's students.size(), since students is an ArrayList
You want to use students.size(). size is a method on List types, not a property (like length is on arrays).
Also, in the constructor, you have this reversed:
MaxCapacity = amountstudents;
it should be:
amountstudents = MaxCapacity;
Related
I'm not sure why, but I'm having a problem launching the code that I put together. For some reason, the code shows fatal errors when I enter a parameter within the methods. I have checked it several times but could not figure out what I did wrong.
Any advice would be appreciated.
public class songcode
{
/**
* #param args the command line arguments
*/
public class Songwriter{
private int song;
//variable for the amount of songs played
private int royalty;
//variable for the amount of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public int Adding_song(){
song = song + 1;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int Requesting_check(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
public static void main(String[] args){
}
}
}
See the comments for some quick help :)
public class SongWriter {
private int song;
//variable for the number of songs played
private int royalty;
//variable for the number of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public SongWriter(int myFavSong){
//define default values for vars above
this.song = myFavSong;
//'This' references the Songwriter object not required but useful practice.
}
// Lower case first word upcase second : camelCase
public int addingSong(int numSongs){
song = song + numSongs;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int requestingCheck(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
// The main method shouldn't be nested another class
public static void main(String[] args){
//In java because our variables and functions are not static
//you need a reference to your SongWrite object
SongWriter songWriter = new SongWriter();
// Notice I modified your function to take in an int as a param
songWriter.song = addingSong(5);
System.out.println(songWriter.song);
}
}
because of lack information it is a little hard for us to solve your problem. Please provide us exacly what steps did you take and what errors did you get.
From what i see now, since your are using inner class (class inside of another class), you should make it static:
static class Songwriter{/*your code here*/ }
When you got that you can create an object of that class in your main() by calling your outer class, so in your case it would be:
songcode.Songwriter name = new songcode.Songwriter();
Now you can use your methods that are within your inner class by using name.method() like:
name.Requesting_check();
for(int i = 0; i<200; i++){
name.Adding_song();
}
Personally i would create a new java file called Songwriter.java, add a constructor and work with that, but maybe that's not what you were testing here ;-)
Hope it did help you and please next time provide more detailed informations, so we can give you an exact answer without guessing what's wrong and what exacly do you want to achieve with your code.
I'm having an issue that has been giving me a an error saying java.lang.StackOverflowError: null. My program is sort of like a lottery, a random number is chosen, and based off the number, your item is chosen from a array. Now this works all handy and dandy, but when i try to insert the item received into an inventory. I get that error. Im pretty sure i set up my class wrong but i don't know how to construct an array in a separate class that receives data from another class, and returns the data back to the same class. Enough chit chatting, heres what my code looks like so far. (please dont mind the extra variables as this is a cropped portion of my code)
public class inventory {
private int inventorymain;
public String[] inventorymain() {
String[] inventorymain;
return inventorymain();
}
}
import java.util.Scanner;
import java.util.Random;
public class glue {
public static void main(String [] args) {
inventory inv = new inventory();
allskins a = new allskins();
Scanner s = new Scanner(System.in);
int selection = 0;
int invcount = -1;
Random rand = new Random();
do {
System.out.println(d.menue());
selection = s.nextInt();
if (selection == 1) {
invcount++;
int random = rand.nextInt(208);
System.out.println("You opend a: ");
System.out.println(a.allskins()[random]);
System.out.println("Your item has been put in your inventory, select inventroy from the menue to view all items.");
System.out.println("");
inv.inventorymain()[invcount] = (a.allskins()[random]);
}
}while (selection != 6);
}
}
Thank you
You're entering infinite recursive loop calling inventorymain()
public class inventory {
private int inventorymain;
public String[] inventorymain() {
String[] inventorymain;
return inventorymain(); // recursive call here without escape condition
}
}
It's better to keep the method name and variable name different to avoid such cases.
I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY#foo.com
The output:
NAME: Happy
EMAIL: HAPPY#foo.com
I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
import java.util.ArrayList;
import java.util.Scanner;
public class Program5 {
void loadContacts()
{
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
scan.close();
}
void printContacts()
{
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
}
Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
private String name;
private String mail;
public Program5(){}
void loadContacts(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a name and a mail like this : name email#email.com (separate with ' ')");
String[] line = scan.nextLine().split(" ");
while(line.length!=2){
System.out.println("Again, enter a name and a mail like this : name email#email.com (separate with ' ')");
line = scan.nextLine().split("/");
}
this.setName(line[0]);
this.setMail(line[1]);
scan.close();
}
void printContacts() {
System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
}
public static void main(String[] args) {
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
public void setName(String name) {
this.name = name;
}
public void setMail(String mail) {
this.mail = mail;
}
}
In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)
You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;
The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String arr[] = input.split("\\s+");
Name = arr[0];
Email = arr[1];
scan.close();
}
And finally on void printContacts().
void printContacts()
{
System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}
Here is the code runnig: http://ideone.com/mjyfHK
You can do a variety of things.
You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.
or
You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.
I have Arraylist of objects ArrayList<Product> productDatabase. The object contains a String and a double and then these objects will be added to the productDatabase by addProductToDatabase(); as follows:
public void addProductToDatabase(String productName, double dimensions); {
Product newProduct = new Product(ProductName, dimensions);
productDatabase.add(newProduct);
}
I also want to make an Arraylist<ProductCount> productInventory which counts how many Product are accounted for. Before it can add to ArrayList<ProductCount> productInventory however, it should first check if the object details exist in the productDatabase while running addProductToInventory()
public Product getProduct(String name) {
for(i = 0; i < productDatabase.size(); i++)
if(productDatabase.get(i).contains(name) //Error: cannot find symbol- method contains.(java.lang.String)
return productDatabase.get(i)
}
public void addProductToInventory(String productName, double quantity)
{
Product p = getProduct(name);
productCount.add(new ProductCount(o, quantity));
}
Assume that you always have different objects (so nothing will have the same name), but you're always unsure of the dimensions (so when you input the same producttName + dimensions you edit the dimensions in it).
At the end of the day, you have to put all the items in it a large box and report what you've inventoried, so you also have a getProductQuantityTotal() and you have to getProductDimensionTotal()-- as the name suggests, get the total of number of objects you've counted, and the sum of the dimensions.
What do I have to add/change/remove about this code? Don't consider syntax first (because BlueJ checks for common syntax errors and I just typed this by hand). I'm sure that I'm missing a for statement somewhere, and I'm probably misusing contains() because it won't recognise it (I have import java.util.*; and import java.util.ArrayList;)
To answer the question in your post title: How to find a string in an object, for a list of those objects, here is some sample code that does this:
First, I created a trivial object that has a string field:
class ObjectWithStringField {
private final String s;
public ObjectWithStringField(String s) {
this.s = s;
}
public String getString() {
return s;
}
}
And then a code that populates a list of it, and then searches each for the string. There's no magic here, it just iterates through the list until a match is found.
import java.util.List;
import java.util.Arrays;
/**
<P>{#code java StringInObjectInList}</P>
**/
public class StringInObjectInList {
public static final void main(String[] ignored) {
ObjectWithStringField[] owStrArr = new ObjectWithStringField[] {
new ObjectWithStringField("abc"),
new ObjectWithStringField("def"),
new ObjectWithStringField("ghi")};
//Yes this is a List instead of an ArrayList, but you can easily
//change this to work with an ArrayList. I'll leave that to you :)
List<ObjectWithStringField> objWStrList = Arrays.asList(owStrArr);
System.out.println("abc? " + doesStringInObjExistInList("abc", objWStrList));
System.out.println("abcd? " + doesStringInObjExistInList("abcd", objWStrList));
}
private static final boolean doesStringInObjExistInList(String str_toFind, List<ObjectWithStringField> owStrList_toSearch) {
for(ObjectWithStringField owStr : owStrList_toSearch) {
if(owStr.getString().equals(str_toFind)) {
return true;
}
}
return false;
}
}
Output:
[C:\java_code\]java StringInObjectInList
abc? true
abcd? false
In the real world, instead of a List, I'd use a Map<String,ObjectWithStringField>, where the key is that field. Then it'd be as simple as themap.containsKey("abc");. But here it is implemented as you require. You'll still have quite a bit of work to do, to get this working as specifically required by your assignment, but it should get you off to a good start. Good luck!
I have to write a program with 3 classes and lots of different methods.
I've written a simpler example to try and get an idea where I am going wrong
First class (music) is defining a music object with three data types. And should have a method to print the contents of an array.
the second class (musicArray) has all the data for the array and should build the array when the third class tells it too.
the third class(searchclass) has the main method it should tell the second class to make the array then with user input search the array for songs that match the rating.
import java.util.Arrays;
public class Music extends musicArray {
private String songTitle;
private double songLength;
private int rating;
static String everything;
public Music(String songTitle, double songLength, int rating) {
this.songTitle = songTitle;
this.songLength = songLength;
this.rating = rating;
}
public String getsongTitle()
{
return songTitle;
}
public double getsongLength()
{
return songLength;
}
public int rating()
{
return rating();
}
#Override
public String toString() {
return "music{"+ "songTitle= " + songTitle + ", songLength= "
+ songLength + ",rating=" + rating + '}';
}
public Music[] printsonglibrary(char[][] songDetails){
for (int count = 0; count <= 6; count++)
{
return System.out.println(songDetails[count]);
System.out.println(" ");
}
}
}
public class musicArray extends Searchclass{
static Music song1 = new Music ("achy breaky", 5.32, 10);
static Music song2 = new Music ("billy",1.2, 8 );
static Music song3 = new Music ("hello", 1.5, 9 );
static //Create array and make posistion 0 = song1
Music[] songDetails ={song1,song2,song3};
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
for(int count = 1; count <= songDetails.length; count++){
system out put for debugging
System.out.println(songDetails.length);
System.out.println(songDetails[count - 1]);}
}
/* public String songSeach(){
System.out.println("what rating of song do you want to search for?");
Scanner keyboard = new Scanner(System.in);
int searchValue = keyboard.nextInt();
if searchValue == rating in array use the printsonglibrary
method in the music class to print the array entry
*/
}
}
If I have the main method in the musicArray class I can print the array
So the question is how do I make the Songdetails array available in the seachclass?
You shouldn't directly expose any variables of one class to another. Instead consider giving the MusicArray class (note that by convention class names should begin with a capital letter) a public method, say public void printOutSongDetails() that would print out the contents of the array. Your main method can then call this method off of the MusicArray object that it has created. e.g.,
Edit 1
Also, the Music class should most definitely not extend the MusicArray class for there is no way that a Music object should behave like a MusicArray object. And on the same token, MusicArray should not extend the SearchClass.
Edit 2
Note that there are several other significant issues with your code that each one would prevent it from compiling, and this suggests that you should modify how you program (if you can't use an IDE). Try to compile early and often, and only add new code to the program after fixing any compilation errors so that the current code base compiles.
Edit 3
A small code example of what I was describing above.
class SearchClass {
public static void main(String[] args) {
MusicArray musicArray = new MusicArray();
musicArray.addMusic(new Music("Foobars Unit", 10.4, 5));
musicArray.addMusic(new Music("Spamalot", 11.0, 7));
//... etc ...
musicArray.printOutSongDetails();
}
}
Also, you'll probably not want those static Music variables but rather give MusicArray a method to add Music to its array, a public void addMusic method that accepts a Music object as a parameter.
One way is to make it public public Music[] songDetails ={song1,song2,song3};
A better way is to provide getter:
public Music[] getSongDetails() {
return songDetails;
}