Write a static method named listCountriesOfOrigin, to be added to the Bowl class, which is passed an array of Bowl objects, and prints to the console in a column the country of origin of each of Bowl objects in the array.
This is my code but is not right and the only compilation errors I am getting is "The system has detected compilation errors." So it is not helping me much. Am i on the right path?
public static String listCountriesOfOrigin (Bowl[] bowls) {
for(int i = 0; i < Bowl.length; i++) {
String origin = bowls[i].getOrigin();
return origin;
}
}
(.getOrigin) is already a declared method that returns the origins of the objects from the array.
for(int i = 0; i < Bowl.length; i++) // `Bowl` is the object name
shouldn't this be
for(int i = 0; i < bowls.length; i++) // bowls is the name of the array of Bowl objects passed to your method.
Also there should not be a return statement inside your for. According to your requirements, your method should print those values on the console.
Hence, make your method return void and instead of the return in the for loop, have a System.out.println(origin);
Related
The ArrayList needs to be set to static. I created a getter method in the main class (CityMenuCreate).In the second class, I do call the method and when I try to create a for function, it doesn't recognize the list.
The method I created in the first class (CityMenuCreate)
public static ArrayList getCityList() {
return cityList;
}
The part of code I'm trying to call the method in the second class
CityMenuCreate.getCityList();
for(int i=0; i< **cityList.size();** i++) {
}
It gives me an error in the cityList.size();. Is there a syntax problem in the for function?
You're ignoring the return value of CityMenuCreate.getCityList(). You either need to save it to a local variable:
List cityList = CityMenuCreate.getCityList();
for (int i = 0; i < cityList.size(); i++) {
// code
}
Or just use it directly from that method:
for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
// code
}
In the above example, you've declared your getCityList() method as static, not your Arraylist. Hence you cannot access your Arraylist in a static way. You either declare your Arraylist static or in your for loop you call the method like so:
for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
//Your code goes here
}
I'm trying to make a booking system for a hotel using the MVC dp. I have a class with a fixed arraylist of rooms (from 1-25) inside the model and class in which I have the showAvailableRooms method in the controller package . I'm asking my View to print out the available rooms but the only thing it prints out is two square brackets ([]).
P.S. The get OccupiedRoom is another method I have in my bookinglist class (model). It checks if the dates you pass it as arguments are a problem to already existing bookings,if it is then it checks if the room is already in that occupied list and if it isn't it adds it to the list.
public void showAvailableRooms(MyDate arrivaldate, MyDate departuredate) {
ArrayList<Room> availablerooms = new ArrayList<Room>();
for (int i = 0; i < 25; i++) {
for (int j = 0; j < l.getOccupiedRoom(arrivaldate, departuredate).size(); j++) {
if (h.getRoom(i) != l.getOccupiedRoom(arrivaldate, departuredate).get(j)) {
availablerooms.add(h.getRoom(i));
} else if (l.getOccupiedRoom(arrivaldate, departuredate).size() == 0) {
System.out.println(h.getAllRooms());
}
}
System.out.println(availablerooms);
}
As i said in comment [] means your list is empty.
you add elements to availablerooms only in your inner loop, but if l.getOccupiedRoom returns you empty list, then code inside inner loop won't be executed, and no empty rooms will be added.
two square brackets ([]). Means that availablerooms doesn't have any entry. Either there are no available rooms, or it isn't getting populated correctly. Please check your logic.
I have this method here:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota) {
boolean aprovaAluno = false;
for(int i = 0; i < materia.length; i++) {
materia[i] = codigoAluno;
for(int j = 0; j < materia[i].length; j++) {
materia[i][j] = codigoMateria;
for(int k =0; k < materia[i][j].length; k++) {
materia[i][j][k] = nota;
if(materia[i][j][k] > 7.0) {
aprovaAluno = true;
}
}
}
}
return aprovaAluno;
}
I'm supposed to call it giving three arguments, #1 student code, #2 subject code and #3 grade. I had declared them as "double" in the method, but Eclipse highlighted it as "cannot convert from double[] to double", so it suggested me to change from this:
boolean exibirAprovacao(double codigoAluno, double codigoMateria, double nota)
To this:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota)
And now Eclipse gives me an error when I'm calling my method:
aluno01.exibirAprovacao(codigoAluno, codigoMateria, nota);
Stating that
the method arguments are not applicable to the ones I'm passing
This is my array declaration:
double[][][] materia = new double[3][1][1];
This is an assignment that I have (starting Java + OO now). Any feedback is really appreciated.
First, you must review the logic of your program: If the method is supposed to find out if a certain student of a certain grade has aproved a certain subject, it should search one single value into the materia multi-array. I insist: It must search for a value, not fill in the data.
Second: Based upon the same assumption, to perform such a search, it would be enough if the method received three single parameters.
If Eclipse suggest you to change any method's firm, first understand what is the cause of the error. And do not accept suggestions without being aware of the implications (In this case, I'm afraid you shouldn't have accepted).
I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!
I've obtained an ArrayListof string for user inputted keywords now I'm trying to see if those keywords are present in the separate elements of another arraylist which is a catalogue of books. My code is shown below and the compiler keeps saying cannot find symbol when i compile the following code:
edit: i've changed the code as follows
ArrayList<Book> catalogue; //was defined in another class
ArrayList<String> keywords;// was created in a driver class through user input
public ArrayList<String> getTitlesContainingKeyword(String keyword){
ArrayList<String>results = new ArrayList<>();
for (int i = 0; i < keywords.size(); i ++) {
for (int j = 0; j < catalogue.size(); j ++){
if (catalogue.get(j).contains(keywords.get(i))) // the contains in this line is giving the error
{
results.add(j);
}
}
}
return results;
}
it appears that the main problem is that catalogue is a book arraylist and keywords is a string arraylist
You should simply check if the keyword exists or not. Why are you using get method ? Simply pass in the String to the contains, completely.
What I mean to say is:
1. Get the keyword.
2. Check if it indeed is a valid keyword by calling the contains() on your keywords ArrayList. If it returns false, do not proceed to search the catalogues.
3. If it is, go over each catalogue and call its contains to see if the keyword is contained in that catalogue.
Your logic seems to be wrong in the code snippet.
public String getTitlesContainingKeyword(String keyword){
for (int i = 0; i < keywords.size(); i ++) {
for (int j = 0; j < catalogue.size(); j ++){
if (catalogue.get(j).contains(keywords.get(i))) {
results.add(j); // << who is results
}
}
}
return results;
}
The error is being given by the compiler because you havn't declared results in your method. Compiler doesn't know what is this results, neither do you, nor me.
If it is supposed be an ArrayList<String>, then declare and create it as such.
Change your method return type to ArrayList<String> instead of String
public ArrayList<String> getTitlesContainingKeyword(String keyword){
ArrayList<String>results = new ArrayList<>();
for (int i = 0; i < keywords.size(); i ++) {
for (String catLog: catalogue){
if (catLog.contains(keywords.get(i))) {
results.add(catLog);
}
}
}
return results;
}