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!
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'm new to Java ans struggling with Arrays. I need help with an array code. There are 20 errors but I can't seem to find them (except 7). Also, I'm new to StackOverflow so sorry for the format.
Code is:
public clas ArrayProcessing
{
public void main (String [] args)
{
int iElement = 0,
int iSmallest = 0,
int iPossible = 0;
String strElements, strSmallest, strPossibles = "";
strElements = joptionPane.showInputDialog("How many elements would you like to be included in the array?");
iElements= Integer.parseInt(strElements);
strSmallest =joptionPane.showInputDialog("What would you like the smallest number in the array to be?");
iSmallest = Integer.parseInt(strSmallest);
strPossibles = joptionPane.showInputDialog("How many possible unique numbers would you like to have?");
iPossibleS= Integer.parseInt(strPossible);
int[] intArray = int[iElement];
displayArray(intArray[0]);
loadArray(intArray, iSmallest, iPossbles)
displayArray(intArray);
}
public static void loadArray(int intArray, int iSmallest, int iPossibles)
{
for (index =0; index < intArray.length(); index++)
{
intArray[index] = iSmallest + (int) (Math.random()* iPossibles);
}
}
public void displayArray(int[] intArray)
{
String strOutput="";
for (iCounter = 0, iCounter<intArray.length, iCounter++);
{
Output += intArray[iCounter] + "";
}
jOptionPane.showMessageDialog(null, "These are the values in your array: \n" + strOutput, "Arrays", JOptionPane.INFORMATION_MESSAGE);
}
You DEFINITELY need to learn the basics. Get an IDE to display the errors. Eclipse or someone suggested BlueJ (I haven't heard of it) but it will help you. Besides showing errors, it can format your code, too. You can click on the error and it will go to the error line.
use semicolons instead of commas.
If you have a "{" following a for loop, don't use semicolon.
To use swing components (i.e. JOptionPane) you need to have a JFrame to display them in.
Indenting is important for YOU and those reading the program. Makes it a lot easier to determine scope.
In a nutshell, you have the concept of programming, but you don't have the basics and you need that first. Start off with an example of, say, JOptionPane and expand on it to include your code.
Good luck. And hang in there. We've all been where you are, but we stuck with it.
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
I'm teaching programming to beginners (starting at 12-15 years old) and one of the choices we made (because it was natural in Python) was to teach the notion of "repeating an action" before the notion of variables.
We warted in Python with
for loop in range(10):
without speaking about variables of arrays and in C++ with
#define repeat(nb) for(int _loop = 0 ; _loop < (nb) ; _loop++)
The idea was to hide the complexity of a classical loop in order to insist on the "repeat" part. We are not hiding from the students the fact that "repeat(10)" is not a part of C++,
it's just a way to simplify the learning.
In Pascal we can't do much more than
for loop := 1 to 10 do
but that's ok because its's not that difficult to remember.
I was looking for something similar in Java and I found that :
import java.util.List;
import java.util.AbstractList;
class Range {
public static List<Integer> size(final int end) {
return new AbstractList<Integer>() {
#Override
public Integer get(int index) {
return 0 + index;
}
#Override
public int size() {
return end;
}
};
};
}
public class Main {
public static void main(String[] argv) {
for (int loop : Range.size(10)) {
System.out.println("xx");
}
}
}
The
for (int loop : Range.size(10))
is still easier to remember than
for(int loop = 0 ; loop < 10 ; loop++)
but there is two problems :
two variables are needed for imbricated for loops : I dont think we can do much about that
we are having warnings because the variable loop is not used
Do you see a better solution that what we have ?
Once again, we only want to provide some "tool" at the beginning phase in order for the students to "repeat" actions, before knowing anything about "variables". We are not hiding from them that's is not in the langage and after a few exercises (~80-100) we are asking them to use the real syntax.
We have approximately 20 exercices before introducing variables : some about printing texts but mostly we are providing one library with objects you can manipulate (hence the variables are hidden in the object state). You can think of the "logo-turtle" for example. This way the notion of "loop" can be manipulated and "seen" before introducing explicit variables and you can have interresting exercises really fast.
One example, in Python, where you want to visit every case of a 10x10 table once and only once and then be back at your starting point (lower-left corner) :
from robot import *
top()
for loop in range(4):
for loop in range(8):
top()
right()
for loop in range(8):
bottom()
right()
for loop in range(8):
top()
right()
for loop in range(9):
bottom()
for loop in range(9):
left()
This exercise is not that easy but the syntax is really simple and allow the student to concentrate on the "algorithmic" part and not the "langage" part.
After a few exercises the students are getting interrested and we can introduce more syntax and more difficult concepts like the variables.
Do you really need to use Java for those exercises? If other languages works for you then why not to use them? You can always move to Java when you students know basics like variables.
I agree that variables can be quite confusing from beginners - especially that their value can change all the time, it is not something people are used from algebra where values don't change once "assigned".
If you want to use Java, you could use while loop which seems to fit better. One dirty trick how to avoid use of variable is following code - it use StackTraceElement instead of variable.
It prints
Hello A
Hello B
Hello C
Hello C
Hello C
Hello B
Hello C
Hello C
Hello C
Hello A
Hello B
Hello C
Hello C
Hello C
Hello B
Hello C
Hello C
Hello C
Hello A
Hello B
Hello C
Hello C
Hello C
Hello B
Hello C
Hello C
Hello C
Here is full source. main(Strinng[] args) method is code with loops, rest is supporting code.
import java.util.HashMap;
import java.util.Map;
public class Repeater {
public static void main(String[] args) {
while(range(3)) {
System.out.println("Hello A");
while (range(2)) {
System.out.println("Hello B");
while (range(3)) {
System.out.println("Hello C");
}
}
}
}
public static boolean range(int size) {
return Range.range(size);
}
public static class Range {
static Map<StackTraceElement, RangePosition> ranges = new HashMap<StackTraceElement, RangePosition>();
public static boolean range(int size) {
final StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];
//System.out.println(stackTraceElement);
RangePosition position = ranges.get(stackTraceElement);
if (position == null) {
position = new RangePosition();
position.size = size;
ranges.put(stackTraceElement, position);
}
final boolean next = position.next();
if (!next) {
ranges.remove(stackTraceElement);
}
return next;
}
}
public static class RangePosition {
int current,size;
boolean next() {
current++;
return current <= size;
}
}
}
But I'd prefer to use some language which supports this naturally.
I would always introduce variables first. What are you going to do inside the loop without knowledge about variables ?
Apart from that maybe it would be easier to use a while loop. The head of a while loop is much easier and doesn't require variable definitions.
This is very simple to understand:
while (do_the_loop){
//this is repeated
}
Java really is not suitable for this kind of task because it does not allow for functions to be passed.
The only way I can think of doing this without variables would be with an interface:
private static void repeat(int times, DoStuff what) {
for (int i = 0; i < times; i++) {
what.doIt();
}
}
private interface DoStuff {
public void doIt();
}
And then use it this way:
repeat(5, new DoStuff() { public void doIt() {
System.out.println("xx"); // whatever needs to be done
}});
Which would be without variables but quite confusing at the beginning.
This is not really what you are searching for, but here is my opinion and how I would teach it. (Beware, I'm not a teacher at all :D)
Aren't there two different courses for this: Algorithms and Programming? In programming, you really should start off by teaching them the variables. It's not difficult at all. And I don't think that 20 exercises about algorithms are going to be that interesting for them. I think they will be more attracted to the power of computing something than either writing for loops inside each other. Writing a simple program that computes some summations and multiplications et cetera will do to introduce the idea of primitive variables. Then I would introduce the for loop. Demonstrate by printing 10 times some text in combination with the variable used in the for loop:
for (int i = 0; i < 10; ++i)
// Tell them that the 'i' is a variable as you explained before.
{
System.out.println("This is line " + i);
}
Then writing an application that computes the factorial of a hardcoded number will be interesting, I think. This way, most of them will hopefully get the idea of working with variables. Then try to explain scopes.
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; ++i)
{
factorial = factorial * i;
}
System.out.println(number + "! = " + factorial);
if you have a limit defined you have to use a while structure
while(myval < mylimit){
//do something
myval++;
}
but when the limit is unknow then you should use for or for each
for (int i =0; i< list.size();i++)
{
}
of by objects
for each (String myString : myStringArray){
}
Saludos
I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.