#Help understanding Arrays and Methods
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
Arrays in Java are a way to store multiple values of the same data type under one variable name. They can be of primitive types like int or double, or objects like String.
To declare an array in Java, you specify the type of elements it will hold, followed by square brackets [] and the array name. For example, int[] numbers;
To initialize an array, you can use the "new" keyword followed by the data type and the size of the array in square brackets. For example, numbers = new int[5];
Methods in Java are blocks of code that perform a specific task and can be reused throughout your program. They are defined by specifying a return type (void if no return value), method name, and any parameters it may take.
To call a method, you use its name followed by parentheses and any necessary arguments. For example, myMethod(argument1, argument2);
You can pass arrays as parameters to methods just like any other variable. This allows you to manipulate arrays within methods without modifying them outside.
To access elements in an array, you use square brackets with the index position inside. Arrays start at index 0. For example, numbers[0] = 10;
Practice writing code using arrays and methods to get more comfortable with them. You can also refer to online resources or textbooks for more in-depth explanations and examples. Good luck with your final exam!
Do you have an example that you don't understand?
I guess a specific one for methods is what does in the parenthesis in a method.
public static int Test(not sure what to put here)
for arrays I am just struggling how to set them up and how to use them in for/ while loops for example.
the final is going to have coding questions so I just want to be able to be comfortable enough to use them in any scenario if that makes sense
think of a method as a little helper living in your program, it does a specific job and you can call it whenever you want
imagine you want a little helper on creating icecream!
here's what it would look like:
public String makeIceCream(String flavor) {
return "Here's your " + flavor + " ice cream!";
}
we use "public" so that everyone in the program can use it (we can share it!), we use the "string" argument so that it returns a string, you see "String flavor" in the brackets? that's the constructor, you tell it what you want the flavour to be when you call the method
Detected code, here are some useful tools:
System out
[Nothing]
Why does my bot not work :(
so if i wanted vanilla when calling the method I would do makeIceCream(Vanilla) and the result would be "Here's your vanilla ice cream!" ?
thing of an array as defining a variable, but instead of just having one string, integer, e.g int x = 5, we can store multiple
in other words, think of it like a tray or a box, you can store multiple objects in one box/tray
for example, let's say i have a car dealership, and i need to store all of my cars, in java i could use an array for this:
String[] cars = {"Red Car", "Blue Car", "Green Car"};
we use String as the data type and a set of "[]" to the end, to insure it's defined as an array, we then set the array name and use a set of curly brackets to store the information
If you put that inside a variable, yeah you can print it out
or to print it out directly you could:
System.out.println(makeIceCream("vanilla"));
The parameters are basically a variable that has the value of whatever you give it
or
String icecream1 = makeIceCream("vanilla");
also don't make the mistake many people do with arrays and try and print out the entire thing in one print statement,
example of a mistake:
System.out.println(cars);
this would return something like S:4744893 if I Remember correctly the "S" is the data type and the numbers is the hashcode
you would need to import the arrays class using:
import java.util.Arrays
and then print it out like so:
System.out.println(Arrays.toString(cars);
or if you cant remember the exact class you want to import, a cheat is to do
import java.util.*;
which imports everything from the "util" class
so arrays, scanners, etc
what does the .toString() do in this instance?
toString() turns it into a string, printing out an array on its own like the mistake exampled above will return it's hashcode
it's annoying, but you have to do it
it bassically turns the haschode into human readibality iirc
it basically takes all the elements from the array and puts it in a set of square brackets
ohh ok that makes sense
another issue with methods for me is when calling I will sometimes get the error that the variable isnt established or this variable already exists. I dont know if this has something to do with passing or not but it stumps me
i think I can understand the issue and this is most likely because you've done this:
public class Main
{
public static void main(String[] args)
{
String icecream1 = makeIceCream("Vanilla");
}
public String makeIceCream(String flavor) {
return "Here's your " + flavor + " ice cream!";
}
}
Detected code, here are some useful tools:
this happens because the "makeicecream" method isn't static and we're calling it from a static method
you could cheat and do:
public static String makeIceCream(String flavor) {
return "Here's your " + flavor + " ice cream!";
}
which makes it static and would work
Detected code, here are some useful tools:
but it's better to create an objecft of your method
like so:
public class Main{
public static void main(String[] args)
{
Main makemeIcreamCream = new Main();
String icecream1 = makemeIcreamCream.makeIceCream("Vanilla");
}
public String makeIceCream(String flavor)
{
return "Here's your " + flavor + " ice cream!";
}
}
Detected code, here are some useful tools:
ignore the code posted earlier, forgot we were working within the same class
Main makemeIcreamCream = new Main();
creates an instance of main
basically a better way instead of being lazy and making the "makeIceCream" method static
this code will work without issue
hopefully this makes sense
I am sorry, but I do not think we have learned about how to do what you just posted. This is the first class in my universities computer science course and they seem to be doing things differently than how you are.
What have they covered (this is what I have done in my 9th grade computer science class)
it does work, you just didn't asked it to call the method
(if anybody wants to read over my explinations and correct/add feel free to do so)
what do you not understand ?
i have attempted to explain the question in the best way i can
this is too advanced, op merely asked how to use methods
?
This is basic oop
variables only exist where you declared them
The bot didn’t send help with my question
?
they asked a follow up question about errors when using methods in a static main method
i gave two solutions
A bot attempts to answer your question, for me it didn’t
also please can we move this unrelated discussion out of this post i am trying to help OP
@scarlet comet
lets focus on helping OP please
Sure
the book we are using, which isnt very helpful, is Introduction to Java Programming by Y. Daniel Lang. the things we have gone over is number conversion, variables, conditionals, math, math.pow for example, strings, while and for loops, files, methods, and arrays
HI, do you have examples of what they are covering?
Ah okay
wait, you are in the wrong thread
So you are struggling with methods and arrays?
You responded to me, but let’s move
yes and you are being very helpful I appreciate it, most I understood it was just the new stuff that threw me for a loop. I can provide some slides the professor uses if that can give you insight on my current understanding of the topic
You started by writing a message in this thread, this is the wrong thread, please go to your thread
he kinda just reads and talks about what is on the slides, but somehow avoids explaining whats going on and how everything works
sorry if thats a lot
then what do you not understand ?
Let's break down this example
We have a static method here (not sure why he's using a static method) but a static method means it belongs to the class and not any objects
We have two parameters which are both integers, start and stop
We set the result variable to 0
We now have a for loop, let's break it down
The variable "i" is basically just a counter, imagine it as your fingers when you count, it will increase EACH time the for loop iterates, which means for as long as i (the counter) is less than or eual to the stop variable, it will keep going and adding the counter to the result variable
Finally we have a return statement, this will return the result variable
By iterate I basically just mean to repeat
oh and I forgot to mention that the start variable is set as the counter
how to use methods and arrays in different scenarios
Why don't you, as a practise write a program where you are a pizzaria, make a method for making pizzas where it will take parameters such as toppings, type, and size
For arrays practise, try making an array, and then using a for loop to iterate through each index of the array and print out that index
(Remember that array indexing begings at 0 in java, e.g if an array was:
int[] numbers = {1,2,3,4,5}
Number "1" would be the "0" index
be at the*
Okay. I will post them here when I am done.
oh and to acess a specific index you would use:
numbers[i]
This is also something I could not figure out, and there could likely be someting similar on the test. If you could walk me through it after I do the practices you provided it would help me out a lot. Thank you again for all your help.
👍 This task is pretty hard considering the fact you don't yet fully understand arrays and methods, but I'll assist on it
let me know if you have any issues during the practises I provided!
this problem was pretty challenging since I had to write the entire code and wasnt given some of the code to me like your professor did here
however I've solved it:
https://github.com/WildRagers/isIdentical-Problem/tree/main
if you want to take a look
@viscid sandal please don't do peoples homework for them.
sry I forgot to mention that I had already turned in the homework before asking them that
I could not figure it out so I asked for help. Was not using the helper to get a good grade. I want to learn
I can provide the grade if need be to clear up any confusion or doubt
@viscid sandal done with the first one
In this case you have two tasks.
- Read the file into two arrays. The first line has the size of the arrays, and the following lines have two values, one for each array
- Compare the two arrays - and the implementation proposed would be to loop over the first array, seeing if that value is in the second array. If all values of the first array are in the second. Since it doesn't clarify if duplicate values can exist, a complete solution would also need to check if all of the values in the second array are in the first.
Note: When getting interactive input (from a user) with Scanner, you should always use .nextLine(). Using combinations of other methods like .next() and .nextInt() can result in confusing program-flow in the event of bad input.
So just for clarification, I should use .nextLine() over the other two even when I am asking for an int or just a single word?
sorry if that is a silly question. I was taught to use .nextInt() when the user is inputting an int.
You should use .nextLine() always... and then, if you want to try to parse that as an int use Integer.parseInt(scanner.nextLine())
I was taught to use .nextInt() when the user is inputting an int.
It's a common mistake that a surprising number of educational sources repeat.
Yes t's shorter, but it is objectively worse for user input. It only works in trivial cases and can't cope with user data-entry error.
thank you for breaking that down. I am going to implement that into practice going forward
@viscid sandal done with the second
@gritty onyx I would like to get to the point where I am confident enough with java that I could do what you and br1t are doing if asked by someone who needed help. Would that MOOC course be a good start or are there other resources here that would be better to start with?
The MOOC is an excellent place to start.
I had assumed by the fact that he shared the assignment and the way they talked about it, the assignment was already past due date. I also shared a GitHub link just in case they didn’t want to see it, thank you for your concern.
Amazing work I’ll read over the code and give feedback
Great work, have you been taught user input? More specifically the scanner class? If so you could make it so each iteration it will ask the user what they want to change the number at the index position to
This code is good and does work however it would be better if you didn’t make every method static other than your main method, it’s good habit to get out of doing that especially when you get to the stage of calling methods from other classes
but for now it’s completely fine
iirc you can declare the scanner in your class instead of declaring it for every method
however not on my computer atm so can’t write any code now
With these side projects in mind, do you feel more comfortable with methods and arrays?
I do actually. Maybe not enough to tackle those homeworks again yet, but I do feel like im getting there. Both you and talden have super helpful
You absolutely should not create multiple scanners consuming the same input. You should either capture it as shared state (eg a field on an object or, reluctantly, static state) or pass the scanner to each method that needs it.
Exactly this
Are those the only homework assignments? Those were pretty tough even for me but im not proficient in Java
those were the only arrays homework. they tell us to use the book, but the homework is significantly more difficult compared to the examples in the book.
how would I pass the scanner to each method?
I can try write up an example of this, give me a moment, it will take me a bit of time since im on mobile
Unless talden can write one
learning Java for the first time?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
...
foo(in);
}
private static void foo(Scanner in) {
System.out.print("Write something: ");
String line = in.nextLine();
...
}
yes this is my first class on it
public class MyClass {
private Scanner scanner = new Scanner(System.in);
public void readInput() {
System.out.println("Enter some text:");
String input = scanner.nextLine();
System.out.println("You entered: " + input);
}
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.readInput();
}
}
I would have come up with something like this
but I assume your way would be easier to learn
apologies if it’s formatted wrong im on mobile and i can’t embed very well
If they haven't learnt about object state then the passing is easier. But capturing it as object state is better.
have you taken a CS class before?
I assume not because most HS CS classes do java and AP CS is Java iirc
unless it’s different in diff systems
I have not. I recently decided to take up programming
id like to do web development
ah okay
wait front end or backend because Java is only really used as a backend web development tool
if you want front end you should learn html css and JavaScript really
And a full-stack developer will learn both.
I think I will learn both just to have it under my belt, but right now I think ill focus on back end
Applets are no longer supported in any current browser.
They are deprecated from the Java platform as well
I gotta go for a bit, but I am going to try and redo the pizza one to have it pass the scanner to each method. thank you both again for the help yall are great
Speaking about scanners, after that you could try modifying your array project from previously to ask the user each iteration in the for loop for a new value for the index it’s on
so each time it loops basically ask the user to set a new value
Anyways im going to go to bed, gn everybody