Create Instrument Class (Dealing with arrays and methods) - java

The array with the names of strings of the instrument is a required field in the Instrument class, but in order to simplify the program, I will accept solutions in which tuning of an instrument is not done separately on each string. However, if you want to work with each string, a good example is found in the Week 8 Additional Notes, in which another class of instruments represented by Tuba is considered.
Please use Listings 8.3 and 8.4 as models to organize your code for Project 3 in two separate classes, one for defining the instrument, and the other one to test instruments.
Make the methods in the Instrument class to return String, unlike the example in the requirements, where such methods write directly to standard output. This is necessary because it is required that output of the test class be written to a file specified by the user on the command line.
In the test class you must have an array with 10 elements of Instrument type, populate the array with instances of the Instrument class (by using the new operator on the class constructor), and the use a while or for loop to perform tests (i.e. call Intrument class methods) on each array element.
As specified in the requirements, the test class must be started with an argument in the command line:
java Mynamep3tst myfilename.txt
where myfilename.txt is the file where all output must go. This file name should be used in the program as follows (see Listing 14.13):
java.io.File file = new java.io.File(args[0]);
java.io.PrintWriter output = new java.io.PrintWriter(file);
and when you have a message to be sent to the file,
output.println(message);
*My question is every time I try to create a new object of the instrument class within my for loop with the use of the array instrumentContent it causes an error. I cannot understand if I am not allowed to create new objects in this fashion. If I am not allowed to do it this way what is the proper way to do it so that each of my arrays are used?*
class StringInstrument {//begin class
//declare variables
boolean isTuned;
boolean isPlaying;
boolean band;
public String nameOfInstrument;
int numberOfStrings;
String nameofStringsInInstrument[] = {"E", "A", "D", "G", "B"}; //an array of string names
public StringInstrument() {//begin contructor
numberOfStrings = 5;
isTuned = false;
isPlaying = false;
band = false;
}//end constructor
public int NumberOfStrings(int stringNumber){//begin method
System.out.println("The number of strings for the " + nameOfInstrument + " is " + stringNumber );
return this.numberOfStrings = stringNumber;
}//end method
public String InstrumentNameGet() {//begin method
return nameOfInstrument;
}//end method
public void SetInstrumentName (String instrumentName) {//begin getter method
nameOfInstrument = instrumentName;
}//end method
public String InstrumentNameDisplay() {//begin method
System.out.println("Your instrument is the " + nameOfInstrument);
return nameOfInstrument;
}//end method
public boolean PlayInstrument(){//begin method
System.out.println("You are playing your " + nameOfInstrument);
return isPlaying = true;
}//end method
public boolean TuneInstrument(){//begin method
System.out.println("Tune " + nameOfInstrument);
return isTuned = true;
}//end method
public boolean stopTuneInstrument() {//begin method
System.out.println("The" + nameOfInstrument + " is out of tune.");
return isTuned = false;
}//end method
public boolean StopPlayInstrument() {//begin method
System.out.println("The " + nameOfInstrument + " has stopped playing");
return isTuned = false;
}//end method
public boolean PlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " is playing in a band");
return band = true;
}//end method
public boolean StopPlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " has stoped playing with the band");
System.out.println("\n");
return band = false;
}//end method
}//end class
public class RandyGilmanP3 {//begin class
public static void main(String[] args) throws Exception{//begin main
java.io.File file = new java.io.File("RandyGilmanP3.txt");
//create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//Declaring, creating, and intialize arrays
String[] instrumentList = new String [10];
String[] instrumentContent = new String [10];
int[] stringNumber = new int [10];
//input string names into array
instrumentList[0] = "Guitar";
instrumentList[1] = "Violin";
instrumentList[2] = "Bass Guitar";
instrumentList[3] = "Cello";
instrumentList[4] = "Banjo";
instrumentList[5] = "Sitar";
instrumentList[6] = "Rabab";
instrumentList[7] = "Viola";
instrumentList[8] = "Harp";
instrumentList[9] = "Ukulele";
//input string amounts into array
stringNumber[0] = 5;
stringNumber[1] = 4;
stringNumber[2] = 5;
stringNumber[3] = 4;
stringNumber[4] = 5;
stringNumber[5] = 18;
stringNumber[6] = 3;
stringNumber[7] = 4;
stringNumber[8] = 47;
stringNumber[9] = 4;
for (int i = 0; i < instrumentContent.length; i++){//begin for loop
StringInstrument instrumentList[i] = new StringInstrument();
output.println(instrumentList[i].InstrumentNameDisplay());
output.println(instrumentList[i].NumberOfStrings(stringNumber[i]));
output.println(instrumentList[i].TuneInstrument());
output.println(instrumentList[i].PlayInstrument());
output.println(instrumentList[i].PlayInstrumentBand());
output.println(instrumentList[i].StopPlayInstrument());
}//end for loop
}//end main
}//end class

You've declared instrumentList[] as an array of Strings. Your for loop attempts calling the following method on these Strings:
InstrumentNameDisplay()
NumberOfStrings(String)
TuneInstrument()
`PlayInstrument()
PlayInstrumentBand()
StopPlayInstrument()
None of these are methods of the String class.
It looks like what you might be trying to do is build an array of Instruments...

Related

Implementing object parameters in other classes

I'm hoping someone can help me with these two values that have me stuck on a project. I have two classes and this first one generates a 2D array with random values.
import java.util.concurrent.ThreadLocalRandom;
public class Guitar {
private int strings;
private int chords;
public Guitar(int mstrings, int mchords) {
this.strings = mstrings;
this.chords = mchords;
}
private double[][] song = new double[strings][chords];
public void generateSong() {
for (int i = 0; i < song.length; i++) {
for (int j = 0; j < song[i].length; j++) {
song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186);
System.out.printf(" %.2f",song[i][j]);
}
System.out.println();
}
}
}
The number of rows and columns is determined by command line arguments. args[0] is the number of rows, args[1] is the number of columns. I converted them to int variables in the main method class
public class Songwriter {
public static void main(String[] args) {
System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords.");
String args0 = args[0];
int strings = Integer.parseInt(args0);
String args1 = args[1];
int chords = Integer.parseInt(args1);
Guitar guitarObj1 = new Guitar(strings, chords);
guitarObj1.generateSong();
}
}
My problem lies in passing the int variables of the command line arguments to make the 2D array the corresponding size. I know my code isn't completely wrong b/c when I set the strings and chords variables equal to 3 and 4 or whatever in the Guitar class itself, the table prints fine.
Sorry if I seem clueless. My class just covered the first chapter on object oriented programming and I've yet to get the fundamentals down.
This is the problematic line:
private double[][] song = new double[strings][chords];
When you create a new object of your Guitar class, the song array is initialized with whatever the values of strings and chords are at that time, which would (most probably) be 0.
Change it to this:
private double[][] song;
public Guitar(int mstrings, int mchords) {
this.strings = mstrings;
this.chords = mchords;
song = new double[mstrings][mchords];
}
EDIT : OP you just answered your own question :)
It doesn't crash but the only output is the system.out.print in the
first line of the main. I believe it's because the strings and chords
variables default to 0, making the array 0x0, and I'm failing to
change their values

When trying to print out a constructor, I get the constructor name and a time stamp

My name is Chris!
To help improve my java programming skills, I'm trying to make a deck class which is an array of cards, however when printing the constructor for the deck class, I get the constructor name and a time stamp and I am COMPLETELY clueless as to why this is.
Can you help?
public static void main(String args[])
{
System.out.println("Custom Java Card Game- Chris L.");
System.out.println();
Deck deck = new Deck();
deck.addCards();
System.out.println();
System.out.println(deck);
}
That is the code from the main program and here is the deck class:
public Deck() //Deck is an array of cards
{
size = 52;
cards = new Card[size]; //Array of cards up to 52
// addCards();
}
public void addCards(){
for(int k = 0; k < Slength; k++){
for (int m = 0; m < Rlength; m++){
String s = suite[k];
String n = num[m];
int r = rank[m];
String str = Integer.toString(r);
// String fin = "[" + s + "," + n + "," + str + "] \r";
// System.out.print(fin);
Card card0 = new Card(s,n,r); //Makes a card! IS WORKING!
turntoString(card0);
// System.out.println( turntoString(card0) );
cards[k] = card0; //adds card to array! IS WORKING!
// System.out.println(cards); //card0
System.out.println(turntoString(card0));
}
}
and here is the output:
deck.Deck#1f01b29
Can anybody explain to me why this is?
You must override the toString() method in the Deck class, otherwise the default method from Object is used, which doesn't print a very useful text. Perhaps something like this:
#Override
public String toString() {
return "the text that you want to print";
}
You might want to return the values of the attributes in the class, or some other information that you deem useful.
You are printing the object information itself since it doesn't have a toString() method to use in order to print it in a human readable way.
#Override
public String toString() {
return "Any text";
}
Remember, you can override toString, equals( & hashcode) for conveniece
eg.
Comparing an instance of Deck to another deck
#Override
public boolean equals(Object object) {
return this.size == ((Deck) object.size);
}

Returning String Methods in Java?

I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()

In java, how do I store each scanner input in a 'for' loop to another method?

I'm trying to send a variable out of a 'for' loop, and save it to a string in another class, but I just end up with the latest input when doing a system print in the last class. Now I suspect this is because of;
ProcessInput c = new ProcessInput();
But I cannot for the life of me understand how I work around that particular problem.
I realize this could be avoided if I appended latest input to a string, and sendt the string after the loop finished. Alas my assignment is not so. Also I'm quite new at this, so be gentle.
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = userInput.next();
c.paste(feedback);
}
}
}
public class ProcessInput {
public void paste(String feedback) {
String line = "";
line += feedback + " ";
System.out.println(line);
}
}
The line is in the local scope of the method and therefore, it is reset every time the method is called. You need to make it an instance variable, so that for every instance created, it preserves the value for that instance.
public class ProcessInput {
String line = ""; // outside the paste method, in the class
public void paste(String feedback) {
line += feedback;
System.out.println(line);
}
}
The concept that you must understand is java is pass by value and not reference, So you are only passing the new input entered every time to the method "paste".
Simple solution
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = feedback+userInput.next();
c.paste(feedback);
}
}
public class ProcessInput {
public void paste(String feedback) {
System.out.println(feedback);
}
}
It is more important you understand the underlying concept of passing values between methods in java.

How can I call my array to my main class?

I have one class called DVD collection and another one called movies. The method with the array that I'm trying to return looks like this:
public class DVDCollection
{
public static DVD[] collection;
public static void searchForDVD( String DVD[], String a) {
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++) {
System.out.print(DVD[i] + a);
}
System.out.println();
}
}
And I'm trying to call it from my main method like so:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
movies.searchForDVD(DVD);
}
}
But it gives me an error saying cannot find symbol - variable DVD
So what exactly is the problem here?
You're calling
movies.searchForDVD(DVD);
but there is no DVD variable defined in the main method. And BTW, even if there was one, the searchForDVD() method takes two arguments, and not just one.
Also note that the searchForDVD() method is static. So you don't need any instance of DVDCollection to call it. Instead of
DVDCollection movies = new DVDCollection();
movies.searchForDVD(...);
you should use
DVDCollection.searchForDVD(...);
In your main method when calling the searchForDVD method you must pass it an array of strings for the dvds along with the name of the dvd as a string.
At the moment you are passing the variable DVD which you have not declared anywhere in the main method.
Code in main method should be:
String[] dvds = new String[] {"firstDVD","secondDVD","thirdDVD");
String movie = "secondDVD";
DVDCollection.searchForDVD(dvds,movie);
problem 1
movies.searchForDVD(DVD);
the parameter DVD is not defined.
problem 2
public static void searchForDVD(...) is a static method of class DVDCollection you should call it DVDCollection.searchForDVD(...) you don't need the movie object.
You are calling DVD several times in this code. I believe the mistake here is the variable name.
You have defined public static DVD[] collection; which is an array of DVD objects called collection. The variable name is collection and that is what you need to use when referencing the variable.
ie: collection.length instead of DVD.length.
When you say public static DVD[] collection;, you are telling the compiler to create you a public, static Array of DVD objects called collection. At some point this array would need to be initialized. Arrays are initialized in the following format:
DVD[] collection = new DVD[];
or
String[] arrayOfStrings = {"a","b","c","d"};
Another problem is that your method is defined as follows:
public static void searchForDVD( String DVD[], String a)
This method is requiring two arguments, not one. If you are trying to require a String[] array called "DVD" then you should declare as follows:
public static void searchForDVD( String[] DVD, String a)
That declaration says this method takes an array of strings and we'll call it DVD and another String which will be called a.
Make sure to note what your variable type is and what your variable name is.
The type tells java what to expect in the variable, the name is how you access it.
String myString = "string data";
String is the type. myString is the variable name. "string data" is the value assigned to the variable.
What makes sense to me is something like:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
//create an Add function inside DVDCollection which reads lines from a text file into collection
movies.Add("list_of_movies.txt");
// no arguments are needed here imo, just have it print to user to ask for a DVD to search and then search the collection
movies.searchForDVD();
}
}
public class DVDCollection
{
public DVD[] collection;
public void Add(string file)
{
// parse file and add contents to collection
}
public void searchForDVD()
{
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++)
{
System.out.print(DVD[i] + a);
}
System.out.println();
}
}

Categories

Resources