#Help understanding Arrays and Methods

1 messages · Page 1 of 1 (latest)

devout epoch
#

I have my final coming up and I am struggling to understand Arrays and methods still as well as how to implement them into code. Could someone help me understand these topics better so that I can use them in my code or at least understand how they work? Any help is appreciated.

ripe grottoBOT
#

<@&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>.

#
TJ-Bot
I have my final coming up and I am struggling to understand Arrays and methods still as well as how to implement them into code. Could someone help me understand these topics better so that I can use them in my code or at least understand how they work? An

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!

gritty onyx
#

Do you have an example that you don't understand?

devout epoch
#

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

viscid sandal
# devout epoch I have my final coming up and I am struggling to understand Arrays and methods s...

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

ripe grottoBOT
scarlet comet
devout epoch
#

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!" ?

viscid sandal
# devout epoch I have my final coming up and I am struggling to understand Arrays and methods s...

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

viscid sandal
scarlet comet
viscid sandal
#

or

String icecream1 = makeIceCream("vanilla");
viscid sandal
#

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

devout epoch
#

what does the .toString() do in this instance?

viscid sandal
#

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

devout epoch
#

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

viscid sandal
ripe grottoBOT
viscid sandal
#

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

ripe grottoBOT
viscid sandal
#

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!";
    }
}

ripe grottoBOT
viscid sandal
#

ignore the code posted earlier, forgot we were working within the same class

viscid sandal
#

basically a better way instead of being lazy and making the "makeIceCream" method static

#

this code will work without issue

#

hopefully this makes sense

devout epoch
#

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.

viscid sandal
pallid vigil
viscid sandal
pallid vigil
viscid sandal
#

i have attempted to explain the question in the best way i can

scarlet comet
pallid vigil
pallid vigil
pallid vigil
scarlet comet
scarlet comet
#

Normally

viscid sandal
#

i gave two solutions

scarlet comet
#

A bot attempts to answer your question, for me it didn’t

viscid sandal
#

also please can we move this unrelated discussion out of this post i am trying to help OP

#

@scarlet comet

dire fern
#

lets focus on helping OP please

scarlet comet
#

Sure

devout epoch
viscid sandal
pallid vigil
viscid sandal
scarlet comet
devout epoch
pallid vigil
devout epoch
#

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

pallid vigil
viscid sandal
# devout epoch

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

devout epoch
viscid sandal
#

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*

devout epoch
viscid sandal
#

oh and to acess a specific index you would use:


numbers[i]
devout epoch
#

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.

viscid sandal
#

let me know if you have any issues during the practises I provided!

viscid sandal
# devout epoch This is also something I could not figure out, and there could likely be sometin...

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

GitHub

This repository is made to assist people with similiar problems and provide a solution! - WildRagers/isIdentical-Problem

gritty onyx
#

@viscid sandal please don't do peoples homework for them.

devout epoch
#

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

gritty onyx
#

In this case you have two tasks.

  1. 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
  2. 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.

devout epoch
#

sorry if that is a silly question. I was taught to use .nextInt() when the user is inputting an int.

gritty onyx
#

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.

devout epoch
#

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?

gritty onyx
#

The MOOC is an excellent place to start.

viscid sandal
viscid sandal
viscid sandal
viscid sandal
# devout epoch <@1197596974334095432> done with the first one

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

viscid sandal
#

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?

devout epoch
gritty onyx
#

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.

viscid sandal
devout epoch
devout epoch
viscid sandal
#

Unless talden can write one

viscid sandal
gritty onyx
#
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();
    ...
}
devout epoch
viscid sandal
#

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

gritty onyx
#

If they haven't learnt about object state then the passing is easier. But capturing it as object state is better.

viscid sandal
#

I assume not because most HS CS classes do java and AP CS is Java iirc

#

unless it’s different in diff systems

devout epoch
#

id like to do web development

viscid sandal
#

ah okay

viscid sandal
#

if you want front end you should learn html css and JavaScript really

gritty onyx
#

And a full-stack developer will learn both.

devout epoch
viscid sandal
#

sounds good unless you want to do Java applets 🤣

#

which flopped

#

anyways

gritty onyx
#

Applets are no longer supported in any current browser.

#

They are deprecated from the Java platform as well

devout epoch
#

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

viscid sandal
#

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