I get the error message cannot find symbol, symbol: method books(int[], int) when I try to compile the following code.
For further explanation about what I want the code to do, see below the code.
public class books {
public void main(String[] args) {
int searchValue = 0, index;
int refNum[] = new int[4]; // the array
refNum[0] = 4; //numbers to refer to (aka to find)
refNum[1] = 6;
refNum[2] = 10;
refNum[3] = 12;
refNum[4] = 14;
int input = Integer.parseInt(enterValue.getText()); //takes user's input
for (int x = 0; x < refNum.length; x++) {
refNum[x] = input; //Tells refNum value to be
}
searchValue = input;
index = books(refNum, searchValue); //"books" is underlined
if (index != -1) {
binarySearchField.setText("We found: " + index);
} else {
binarySearchField.setText("Sorry! Not Found!");
}
public static Boolean binarySearch(String [] refNum, int left, int right, String search){
//Boolean code for later
}
This program uses binary search to find values stored in array after user inputs number, if they match then the item is successfully found. User inputs desired number in 'enterNumber' which is a TextField. Now in my code )which I'm 78% sure will work if it wasn't for this one little thing) there is an all important that is underlined which shouldn't be, (I've commented beside the line to show)
Now I had thought I was suppose to put the class name there, but apparently since it is underlined that is not the case. Any ideas on what I should be putting there in it's place?
And I apologize for the question may be a bit misleading on what I'm really asking, I just wasn't sure how to word the question.
The line
index = books(refNum, searchValue);
seems to be underlined because you have no method called books that takes an int[] and an int as arguments in your books class definition.
Now I had thought I was suppose to put the class name there Why do you assume you have to put the class name there? Figure out what you are trying to do with this code and then you will understand what goes in that line (at least in pseudocode).
Also it seems like you have a method declared directly inside another method. That is not legal in java. If this is not the case, please show us correct code.
books is your class's name..that might be the reason you are getting this error. You can't call constructor like a method. Change class's name to Books or something else..or change method's name
Related
I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions
I posted this question up earlier and it was pretty much a lazy post as I didn't provide the code I had and as a result got negged pretty badly. Thought I'd create a new one of these ....
I have an array dogArray which takes ( name, secondname, dogname )
I want to be able to change the dogname:
here's my attempt :
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
String namgeChange = rp.next(); {
for (int i = 0; i < dogArray.length; i++){
for (int j = 0; j < dogArray[i].length; j++){
if (dogArray[i][j] == name){
dogArray[i][j] = nameChange;
}
}
}
}
For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.
Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?
Only one loop is necessary, also move your call to next.
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
for (int i = 0; i < dogArray.length; i++){
String nameChange = rp.next(); {
if(!dogArray[i].name.equals(nameChange)){
dogArray[i].name = nameChange;
}
}
}
You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!
I am trying to send two variables from one sketch to another, using the oscP5 library for processing.
The message I am sending is created like this:
OscMessage myMessage = new OscMessage("/test");
myMessage.add(title);
myMessage.add("Zeit");
oscP5.send(myMessage, remoteLocation);
In the second sketch, I receive the data like that:
void oscEvent(OscMessage theOscMessage) {
if(theOscMessage.checkAddrPattern("/test")) {
String title = theOscMessage.get(0).stringValue();
String layoutType = theOscMessage.get(1).stringValue();
addToQueue(title, layoutType);
}
}
And here my simplified addToQueue function:
void addToQueue(String title, String layoutType) {
if(!existsInQueues(title)) {
upcomingHeadlines.add(new Headline(title, printAxis, scrollSpeed, layoutType));
}
}
Every time I start the sketches, I get the error:
ERROR # OscP5 ERROR. an error occured while forwarding an OscMessage to a method in your program. please check your code for any possible errors that might occur in the method where incoming OscMessages are parsed e.g. check for casting errors, possible nullpointers, array overflows ... .
method in charge : oscEvent java.lang.reflect.InvocationTargetException
I have been able to track the problem down to the layoutType-Variable. If I change
String layoutType = theOscMessage.get(1).stringValue();
to
String layoutType = "Zeit";
no error occurs.
That is quite confusing, because both versions should have the same result.
The error message does not help me in any way.
Edit
I have compared the two possible variables like that:
String layoutType = theOscMessage.get(1).stringValue();
String layoutTypeB = "Zeit";
if(layoutType.equals(layoutTypeB)) println("Same String!");
Since gets printed to the console, both have to be the same … I really do not know where to search for an error anymore.
Edit 2
I have wrapped my second sketch in try {...} catch(Exception ex) {ex.printStackTrace();} like that:
void oscEvent(OscMessage theOscMessage) {
try {
if(theOscMessage.checkAddrPattern("/test")) {
if(debug && debugFeed) println("Received message from other sketch.");
String title = theOscMessage.get(0).stringValue();
String layoutTypeO = (String)theOscMessage.get(1).stringValue();
String layoutType = "Zeit";
if(debug && debugTemp) {
if(layoutType.equals(layoutTypeO)) println("IS DOCH GLEICH!");
}
if(debug && debugFeed) println("Parsed Information.");
if(debug && debugFeed) println("-----");
addToQueue(title, layoutTypeO);
}
} catch(Exception ex) {ex.printStackTrace();}
}
That gives me this error as result:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at printer$Headline.useLayout(printer.java:260)
at printer$Headline.<init>(printer.java:188)
at printer.addToQueue(printer.java:407)
at printer.oscEvent(printer.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at oscP5.OscP5.invoke(Unknown Source)
at oscP5.OscP5.callMethod(Unknown Source)
at oscP5.OscP5.process(Unknown Source)
at oscP5.OscNetManager.process(Unknown Source)
at netP5.AbstractUdpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:744)
Edit 4
Constructor for my Headline-Class:
class Headline {
//Define Variables
Layout layout;
String title, lastHeadline;
float yPos, speed;
float transparency = 255;
boolean fullyPrinted = false;
int boundingBoxHeight;
// Initialize Class Function
Headline(String t, float y, float s, String lay) {
title = t;
yPos = y;
speed = s;
layout = useLayout(lay);
boundingBoxHeight = calculateTextHeight(title);
}
You might want to know about useLayout() too, so here it is:
Layout useLayout(String name) {
ArrayList layoutVariants = new ArrayList<Layout>();
int existingLayouts = layouts.size();
Layout chosenLayout;
for(int i = 0; i < existingLayouts; i++) {
Layout currentLayout = (Layout)layouts.get(i);
if(currentLayout.layoutType == name) {
layoutVariants.add(currentLayout);
}
}
if(layoutVariants != null) {
int rand = (int)(Math.random() * layoutVariants.size());
chosenLayout = (Layout)layoutVariants.get(rand);
} else {
chosenLayout = (Layout)layouts.get((int)(Math.random() * existingLayouts));
}
return chosenLayout;
}
There are two problems with your code, and both of them are in your useLayout method.
The first problem is that you are not comparing Stringss correctly on this line:
if(currentLayout.layoutType == name) {
name is a String, and I assume currentLayout.layoutType is too. Two Strings that are equal but not the same will not compare equal under ==. As a result of this, your layoutVariants list will quite probably be empty at the end of the for loop.
This line should read:
if(currentLayout.layoutType.equals(name)) {
See also this question.
The second problem is that you don't correctly handle the case that the layoutVariants list is empty. The problem is on this line:
if(layoutVariants != null) {
layoutVariants will never be null, so the else branch of this if statement will never execute. Because layoutVariants.size() will be zero, rand will always be zero. Trying to get the element at index 0 in an empty ArrayList will give you precisely the IndexOutOfBoundsException you are seeing.
I imagine you want the else block to execute if the layout name given isn't recognised, in other words, if the layoutVariants list is empty, rather than null. In that case, change this line to
if(!layoutVariants.isEmpty()) {
Note the ! (not-operator) before layoutVariants. You want the code under the if statement to run if the layoutVariants element is not empty.
EDIT in response to your comments: a null ArrayList is very much not the same as an empty one. null is a special value meaning that the variable doesn't have an object of a given type.
Let's try a real-world analogy: a shopping bag. If you have an empty bag, or no bag at all, then you have no shopping either way. However, you can put things into an empty bag, and count how many items it contains, for example. If you don't have a bag, then it doesn't make sense to put an item in it, as there's no bag to put the item into. null represents the case where you don't have a bag.
Similarly, a String is a collection of characters, and the collection of characters can exist even if it doesn't contain any characters.
isEmpty() can be used for any collection, and, if you're using Java 6 or later, Strings as well. Off the top of my head I can't name any other classes that have an isEmpty method. You'll just have to consult the documentation for these classes to find out.
I've not worked with Processing much, but I am aware that Processing is built on Java, so I would expect any standard Java method to work. Also, I wouldn't worry about 'clearing' a variable: the JVM is generally very good at clearing up after you. There's certainly nothing I can see wrong with your code in this respect.
EDIT 2 in response to your further comment: ArrayList arr; declares a variable of type ArrayList. However, the variable arr is uninitialized: it does not have a value (not even null) and it is an error to try to read the value of this variable before you have assigned a value to it:
ArrayList arr;
System.out.println(arr); // compiler error: arr might not have been initialised.
Assign null and the code then compiles:
ArrayList arr = null;
System.out.println(arr); // prints 'null'.
It's not often you need to declare a variable and not give it a name, but one common case is where you want to assign different values to the same variable on both sides of an if statement. The following code doesn't compile:
int y = getMeSomeInteger(); // assume this function exists
if (y == 4) {
int x = 2;
} else {
int x = 5;
}
System.out.println(x); // compiler error: cannot find symbol x
The reason it doesn't compile is that each variable x is only available within the braces { and } that contain it. At the bottom, neither variable x is available and so you get a compiler error.
We need to declare x further up. We could instead write the following;
int y = getMeSomeInteger(); // assume this function exists
int x = 0;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
This code compiles and runs, but the value 0 initially assigned to x is never used. There isn't a lot of point in doing this, and we can get rid of this unused value by declaring the variable but not immediately giving it a value.
int y = getMeSomeInteger(); // assume this function exists
int x;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
I'm trying to get back into Java - it's been about 5 years since I studied the basics and I've been lost in the .Net world since.
I'm trying to create a student class below, however the for loop for reading in the integers into the array gets stuck when the program runs.
From my previous knowledge, and from research, the loop seems to be constructed properly and I can't seem to figure out where it's going wrong.
I'm sure it's something silly - as always but I was wondering if someone could point me in the right direction? :)
import java.util.*;
import acm.io.*;
public class Student {
// instance variables
private int studNumber; //Must be between (and including) 0 and 99999999. If input value invalid default to 0.
private String studName;
private int marks[];
/*
* Constructor Student Class
*/
public Student(int studNumber, String StudName, int marks[]) {
// initialise instance variables
if (studNumber >=0 && studNumber<= 99999999) {
this.studNumber= studNumber;
} else {
this.studNumber = 0; //default value
}
this.studName= StudName; // no validation
this.marks = marks;
IOConsole console = new IOConsole();
for (int i = 0; i <= 6; i++) {
marks[i] = console.readInt();
}
}
}
I think that the problem lies here:
for (int i = 0; i <= 6; i++)
{
marks[i] = console.readInt();
}
The only instance where I found a reference to IOConsole was here and it does not seem to be something which is part of the standard Java framework.
If you just need to scan numbers from console, you can use the Scanner class and the use the nextInt() method like below:
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 6; i++)
{
marks[i] = input.nextInt();
}
The loop seems correct. Is it possible the console.readInt() call is blocking, which keeps you stuck in the loop (the IOConsole class is not part of the standard JDK, and I am not familiar with it)
readInt() is waiting for user input
from http://jtf.acm.org/javadoc/student/acm/io/IOConsole.html#readInt%28%29:
Reads and returns an integer value from the user
The problem is with console.readInt(), where another non-stop loop is executing or some other problem with that method
I believe the problem lies in the readInt() part. It's unusual to read input from the Console in a constructor for initializing the attributes, delegate that task to another part of your code and move it outside the constructor.