New to Java and coding in general [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Teacher is making us code and we're legit just a week or so in intro to programming with java and she's already making us do this. I'm absolutely clueless. This is the pseudocode.
Pseudocode
Create variables: speed, time and distance
Store 20 in the variable speed
Store 10 in the variable time
Multiply speed * time and store the result in the variable distance
Display The distance is followed by the value of the distance variable.
Kind regards.

To create a variable, you must tell Java its type and name. Creating a variable is also called declaring a variable. When you create a primitive variable Java will set aside enough bits in memory for that primitive type and associate that memory location with the name that you used. You have to tell Java the type of the variable because Java needs to know how many bits to use and how to represent the value.
This is the list of Java Primitive Data Types:
Notice that the different types get a different amount of space. When you declare a variable, a memory location (sequential number of bits) is set aside for a variable of that type and the name is associated with that location. An integer gets 32 bits of space, a double gets 64 bits of space and a boolean could be represented by just one bit, but the amount of space isn’t specified by the Java standard.
Ok Teo, I got it, but how to declare (create) a variable?
Well my young padawan, you need to specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ;.
Teo, why a semicolon?
Well, like in English, we use a dot to represent the end of a sentence, in Java we use a semicolon ; to show the end of a Java statement.
Teo, how can I know what type should I use?
Good question young one. It depends on your definition. For example, Java uses the keyword int for integer, float and double for a floating point number (a double precision number), and boolean for a Boolean value (true or false) as shown in the image.
Now let's try to make some code, so you can understand:
1. Create variables: speed, time and distance
For your pseudo code let's assume that all the numbers are integer so we will use the type int like this:
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed;
int time;
int distance;
}
}
Because they are all integers you can declare all of them at once in one line using coma , like this:
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed, time, distance;
}
}
Well we have declared our variables but they have not been initialized to any value yet.
2. Store 20 in the variable speed and Store 10 in the variable time
This part of the exercise will assign a value to our declared variables like this:
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed, time, distance;
speed = 20;
time = 10;
}
}
The equal sign here = doesn’t mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here it means store the value in the space (box) associated with the name on the left to the value on the right. In this example, we assigned the value 20 to the variable speed and the value 10 to the variable time.
You can also specify an initial value for the variable by adding an equals sign = followed by the value when you declare the variable like this.
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed = 20;
int time = 10;
int distance;
}
}
Notice that the variable distance has not been initialized, yet.
3. Multiply speed * time and store the result in the variable distance
Remember that a variable holds a value and that value can change or vary. In this example, you can assign the result of multiplying speed and time to the variable distance. You can do this as shown below:
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed = 20;
int time = 10;
int distance = speed * time;
}
}
4. Display The distance is followed by the value of the distance variable.
Finally, you can simply use System.out.println() to send output to standard output (screen).
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed = 20;
int time = 10;
int distance = speed * time;
System.out.println(distance);
}
}
Remember that println() method prints a string inside the brackets. Then the cursor moves to the beginning of the next line.
Also we can use the single line declaration like this:
public class VariableDeclaration
{
public static void main(String[] args)
{
int speed, time, distance;
speed = 20;
time = 10;
distance = speed * time;
System.out.println(distance);
}
}

Related

Java - Why void when I'm storing value in variable

So, the question is. If I'm calling method guess from class - Player and it is a void-type method without return statement in it, how come I'm able to store result of number = (int)(Math.random() * 10) in number variable for 3 different objects (p1, p2, p3)?
I'm little confused about when should I use return statement or void-type methods, because if number = (int)(Math.random() * 10) is giving some results which I want to use, why then I don't need to return this results from a method to pass them to the number variable which I declared in int number = 0;
public class Player {
int number = 0;
public void guess() {
number = (int)(Math.random() * 10);
System.out.println("I'm guessing " + number);
}
}
A void method does not return anything, but it still allows you to do things. (Print to the console, modify variables etc) The void keyword just means that it doesn't return a value. (In void methods you can still use a blank return; to end the method) And because you are modifying your number variable in the GuessGame object the changes you make will stay even though you don't return a variable. Try this simple test to see what I mean:
//In your GuessGame class
int number = 0;
public void foo() {
number++;
}
public static void main(String[] args) {
GuessGames games = new GuessGames();
games.foo();
System.out.println(games.number);
//Outputs 1
}
docs for the return statement
The point is: where is the result of Math.random() * 10 physically stored on your computer when your program is run? You list two options.
Options 1: Instance field
In this case the compiler instructs your operating system to reserve space for a int variable for the whole life of the Player object. The player object may live for microseconds, seconds, minutes, hours, days, months, ... it depends! This storage space is usually find in the RAM of the computer and from Java you can access it with the syntax myPlayer.number as long as you have a Player reference somewhere.
Options 2: Return value
In this case the compiler finds the space to store the result of the computation in a register of the Java virtual machine, that you can mentally map to a register of the physical processor. This value will only at best survive for a couple of processor cycles (there are gazillinos in a GHz CPU, so it's really a tiny little fracion of a second) if you don't store it somewhere else - and if you don't it's lost forever. See the following example:
private int someRandom;
private int gimmeARandom() {
return Math.random() * 10;
}
private int test() {
int someRandom = gimmeARandom(); // --> store the value until end of method
this.someRandom = someRandom; // --> further keep it so we can read it later
gimmeARandom(); // --> what did it returned? We'll never know
}
Void is different than static - void just means the function does not return anything, but it can still be a instance method, i.e. one that is associated with each new instance of a class. I think you're confusing this with the functionality of static, which allows methods to be called without an instance of the class.

Scope of variable instantiated inside a method - Java

Is this code safe in Java?
public class HelloWorld {
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
int y = h.getNumber(5);
int z = h.getNumber (6);
if (y == 10)
System.out.println("true");
}
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
}
My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten.
Is the same code potentially unsafe in C?
The HelloWorld class has no fields, and is therefore immutable. You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument.
Maybe your co-worker is recalling horror stories in C where you can have something like static int number, which "belongs" to the method and which would get overwritten. Or maybe she's thinking about "return by reference"; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call.
Your coworker is correct, sort of, but they apparently misunderstand what is going on.
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z.
I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.

Java instance variables initialization with method

I am a little bit confused about the following piece of code:
public class Test{
int x = giveH();
int h = 29;
public int giveH(){
return h;
}
public static void main(String args[])
{
Test t = new Test();
System.out.print(t.x + " ");
System.out.print(t.h);
}
}
The output here is 0 29, but I thought that this has to be a compiler error, because the variable h should have not been initialized when it comes to the method giveH(). So, does the compilation go through the lines from top to bottom? Why is this working? Why is the value of x 0 and not 29?
The default value of int is 0 (see here). Because you initialize x before h, giveH will return the default value for a int (eg 0).
If you switch the order like this
int h = 29;
int x = giveH();
the output will be
29 29
Compilation in Java doesn't need the method to be declared before it is used. The Java tutorial goes into a bit more detail on initialization.
Here's a way to think about it: the compiler will make a note to look for a method called giveH somewhere in scope, and it will only error if it leaves the scope and doesn't find it. Once it gets to the giveH declaration then the note is resolved and everyone is happy.
Also, the variable initialization for instance variables in Java is moved to the beginning of the constructor. You can think of the lines above being split into two parts, with the declaration for x and h above, and the assignment inside the constructor.
The order of declaration does matter in this case. When the variable x is initialized, h has the default value of 0, so giveH() will return that default value. After that, the variable h is given the value 29.
You can also look at the Java Language Specification sections on Field Initialization and Forward References During Field Initialization.
#Maloubobola has provided the correct answer, but since you don't seem to fully understand yet, let me try to elaborate.
When Test is created, it runs the variable initialization (x = giveH(), h= 29) once. Your misunderstanding may be that variable x is always determined by giveH(), whereas it only determines it's value when x is initialized.
That's why the order of the statements is crucial here; x is initialized before h, and therefore h is 0 when giveH() is called at x's initialization.
It's bad practice to use a method in the field initializer. You can fix this by making h final. Then it will be initialized when the class is loaded.
import java.util.ArrayList;
public class Test {
int x = giveH();
final int h=29;
final public int giveH(){
return h;
}
public static void main(String args[]) {
Test t = new Test();
System.out.print(t.x + " ");
System.out.print(t.h);
}
}
If we do not initialize the value for non static variables like x in this program JVM will provide default value zero for class level non static variables.
Once declared, all the array elements store their default values.
Elements in an array that store objects default to null.
Elements of an array that store primitive data types store:
0 for integer types (byte, short, int,long);
0.0 for decimal types (float and double);
false for boolean;
\u0000 for char data.
Actauls values will come only when we give initialize them

JAVA Square Footage Calculation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}

Java text analysis program

The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
Here is my program:
public class TextfileHW2 {
// initiate(
public static int[] initiate(int[] values){
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
return values;
processing(values);
}
// processing(values)
public static int[] processing(int[] valuez){
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
valuez[x]+=1;
}
}
return valuez;
output();
}
for (Integer u : valuez){
totalticks += u;
}
}
public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
sc.close();
input.close();
}
public static void main(String[] args) throws FileNotFoundException {
static double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
static int totalticks = 0;
System.out.println("What file would you like to open?");
static Scanner sc = new Scanner(System.in);
static String files = sc.nextLine();
static Scanner input = new Scanner(new File(files));
System.out.println("What words would you like to search for? (please separate with a comma)");
static String ticks = sc.nextLine(), tics = ticks.toLowerCase();
static String[] keys = tics.split(",");
static int[] values = new int[keys.length];
initiate(values);
}
My program should be logically right as I wrote it and successfully ran it for a while last week, but the difference with this one (which doesn't work) is that I must use separate methods for each component of the analysis, which shouldn't be too difficult a task considering the program was working before So I naturally tried to split up my program such that I can call my first method (which I called initiate) then my 2nd and 3rd methods called processing and output.
First of all, what does static really mean? I remember my teacher saying that it represents a global variable which I can use anywhere in the program. As you can see I changed every variable to static to perhaps make my task easier.
Also, do I strictly need to use public static + type returned if I'm going to change something?
Let's say I want to change the values of an array (like I do in my program and use public static void) do I need to return something to actually change the values of the array or is it ok to use public static void?
If anyone also has any general pointers for what concerns my methods I would really appreciate it.
Your problem is in your initiate method:
return values;
processing(values);
Once you call return, your method stops. If you are using Eclipse (which I highly recommend), you should have gotten an error saying "Unreachable code," because there is simply no way for the program to execute your processing method.
I also saw this flaw in your output method.
First of all, what does static really mean? I remember my teacher
saying that it represents a global variable which I can use anywhere
in the program. As you can see I changed every variable to static to
perhaps make my task easier.
It depends on the context. There is a good overall description here. The meaning is different when applied to methods, fields, and classes. To say it makes variables "global" is a bit simplified.
Also, do I strictly need to use public static + type returned if I'm going to change something?
I'm a little confused about what you mean. A method declared as public static *return_type* has three separate, independent qualities:
public: It is accessible by any other class.
static: It does not require an instance of the class to function (see above link).
*return_type*: This is, of course, the return type.
These properties aren't really related to "changing something". Unless I misunderstood your question, the answer is: No, the method specifiers and return type have no impact on its ability to change something with the exception that static methods cannot modify non-static fields or call non-static methods of this (there is no this in static methods).
Let's say I want to change the values of an array (like I do in my program and use public static void) do I need to return something to actually change the values of the array or is it ok to use public static void?
What you do in the function is entirely independent of the access specifier and static-ness of it (with the above-mentioned exception that this does not exist in static methods). If your function has any side-effects like changing the values in an array (or any values for that matter), then it does it regardless of public, or static, or its return type.
Check out the More on Classes section of the official language tutorial. It is concise and well-written and should help complete your understanding of the general concepts you're asking about. Check out some of the other tutorials there as well if you'd like.

Categories

Resources