Instantiation Efficiency - Declare Variables To Be Used In A Loop

Sep 6, 2014

Where usually to instantiate and declare variables to be used in a loop. If you declare it outside to be used in the loop it will still be there when the loop is done, never to be used again and is just sitting there taking up memory. However, if you declare it inside the loop, you have the issue of it constantly creating space for said variable, but once it's out of scope it's gone. Is there any advantage performance wise to doing it either way?

View Replies


ADVERTISEMENT

How To Declare And Initialize Variables

Feb 14, 2015

The problem is to figure out the number of cartons needed to box up the strawberries picked by the farmer and his wife. The farmer picks 8.4 lbs per hour and the wife pick 10.8 pounds per hour. They pick from 8 am until 4Pm (8 hours). You can put 20 pounds per box.I understand the word problem and how to declare and initialize variables. I'm just confused how to display the math into java to solve it.

View Replies View Related

JGRASP Won't Allow To Declare Variables As Strings

Oct 10, 2014

Java Code:

import java.util.Scanner;//Imports Scanner
public class operadoreslogicos//imports a public class {
public static void main (String [] args)//defines the state of a class {
Scanner input = new Scanner (System.in);//Inputs a scanner to read user
//keyboard
boolean cierto = true,// Declares variables as boolean and applies a value

[Code] .....

The word string is supposed to turn purple when I type it, but it just stays normal, so it doesn't declare hello and bye as variables.

View Replies View Related

How To Declare ArrayList That Can Hold Int Variables

Mar 26, 2012

Any way of How to declare an ArrayList that can hold int variables?

View Replies View Related

Write A Program That Declare And Initialize Three Floating-point Variables

Oct 3, 2014

Write a program OutCircle.java that declares and initializes three floating-point variables (r, x, y): the first variable represents the radius r of a circle centered at (0,0) and the second and third variables are the coordinates (x, y) of a point in the plane.Your program should print true if the point is outside the circle and false otherwise. Hint: A point is outside the circle when its distance to the center is greater than the radius.

View Replies View Related

Declare Counter With Value Outside For Loop

Mar 29, 2015

Is it possible to declare a counter with a value outside of a for loop?

I have a counter that will end prematurely in a while loop during various iterations and I want to pick it back up in a catch all for loop at the end

Let's say I have a while loop

while(something) {
total++
}

then after I have a for loop that I want to start at total but would rather do that then make a new counter variable.

for(total;total < 20;total++)

Is something like this possible or is this a horrible thing to want anyways?

View Replies View Related

Declare String Inside Of Loop - Use It Outside

Apr 26, 2015

I'm trying to code a little text RPG. I've made a little "personality test", with 4 questions (answers a b c), where every letter stands for a type of personality. The analysis of the result is simple counting of the answers, if you have 3 answers a (4 questions), then a has won. If 2 on a, and 2 on b, a simple Random method shows weather result a or b.

Now... the test should give you a "partner" (imagine the pokemon game with 3 different starter pokemon). I have now 3 string variables, like 3 different partners. They are all declared somewhere outside, but i only need one later.

Like...the test is completed, you have your partner and how can i make now that the program is just showing me my partner? Like...when i type " System.out.println(partner); " (outside of the test loop! ) that i only get the one i got through the test?

I was trying to declare in every loop the partner String with every result. But outside the loop java isn't recognising that String, bcs...ofc...it was declared for the loop. So i had in every if or else if clause a " String partner = anwsA;" and answB and answC, thats why i cant declare them outside.

Short: i need a partner String variable that could have 3 possible results... i jut need one

I'm using Eclipse Luna 4.4

View Replies View Related

How To Make Sum Of Variables In A Loop

Aug 13, 2014

I've looped a method 14 times, each time it focuses on a different person and how many oranges he/she has eaten. I now want to calculate the total amount of oranges eaten and exactly how many oranges are eaten on average, how can I do that?? the amount of oranges eaten is variable, they are determined by what number the user types in.

View Replies View Related

Sorting ArrayList Of Type Int - Overloading Efficiency

Feb 11, 2014

I have a case in which I want to sort two types of ArrayLists (using quicksort) and the method originally coded only accepts a String ArrayList. The problem is that now I want to sort an ArrayList of type int but couldn't . . . so I decided to overload the method. Since it looks very ugly to copy and paste the same chunk of code only to change the method signature I wondered if there is a better way to make this method more dynamic and be able to take in different types of ArrayLists.

My code:

private ArrayList<String> sort(ArrayList<String> ar, int lo, int hi){
if (lo < hi){
int splitPoint = partition(ar, lo, hi);
sort(ar, lo, splitPoint);
sort(ar, splitPoint +1, hi);

[Code] .....

View Replies View Related

Android Racing Game - Algorithm Efficiency

Feb 6, 2014

I am making an android racing game. I have a method that draws the track to the screen, the map is bigger than the screen so i clip the bitmap and draw it to the screen hence to draw the track I have to get the visible track points and then draw them. I have noticed that when I enable drawing the track the game lags quite a bit but when i disable it is smooth as expected the code is below :

public void drawTrack(Canvas canvas) {
if (this.trackPoints != null && this.trackPoints.size() > 0) {
 // get points, convert back to screen coords and add them to array,
// then
// use that arraylist<point> below
getCurrentVisibleTrack();
counter++;
if (this.visibleTrackPoints.size() > 0) {
 
[Code] .....

View Replies View Related

Array Reference Instantiation

May 17, 2014

I am currently learning Java basic concepts and this is a very simple code which produces error depending on the way I write. It is as follows:

package testPackage;
interface ArrayInsideClassShock {
}
class Check{
ArrayInsideClassShock var[]; //Error line
var= new ArrayInsideClassShock[10];
}

Error in eclipse:Syntax error on token ";", , expected

But if I write it as:

package testPackage;
interface ArrayInsideClassShock {
}
class Check{
ArrayInsideClassShock var[]=new ArrayInsideClassShock[10];
}

It doesn't show any error.

View Replies View Related

Generic Instantiation Of A Collection - ArrayList

Nov 18, 2014

So I have a persons class:

public class Person
{
private String name;
private int age;
 public Person (String name, int age) {
this.name = name;
this.age = age;

[Code] .....

And I need to write a simple main method that creates lots of instances of the Person class and adds them to a generic instantiation of a Collection (ArrayList). And I need to make it so I as a programmer can define how many instances to create.

View Replies View Related

How To Improve File Reading Efficiency And Its Data Insertion In Java

Feb 8, 2014

We have an autosys job running in our production on daily basis. It calls a shell script which in turn calls a java servlet. This servlet reads these files and inserts the data into two different tables and then does some processing. Java version is 1.6 & application server is WAS7 and database is oracel-11g.

We get several issues with this process like it takes time, goes out of memory etc etc. Below are the details of the way we have coded this process.

1. When we read the file using BufferedReader, do we really get a lot of strings created in the memory as returned by readLine() method of BufferedReader? These files contain 4-5Lacs of line. All the records are separated by newline character. Is there a better way to read files in java to achieve efficiency? I couldnt find any provided the fact that all the record lines in the file are of variable length.

2. When we insert the data then we are doing a batch process with statement/prepared statement. We are making one batch containing all the records of the file. Does it really matter to break the batch size to have better performance?

3. If the tables has no indexes defined nor any other constraints and all the columns are VARCHAR type, then which operation will be faster:- inserting a new row or updating an existing row based upon some matching condition?

View Replies View Related

Multi-dimension Array Declaration And Instantiation?

May 17, 2015

Whilst pre-preparing for java certification, one of the online mock exams has slightly confused me by saying my answer was incorrect for multi-dimension array 'declaration and instantiation'.

This is one of the answers i chose - which was marked as incorrect

a)
int[][] array2d = {{123}, {4,5}};

Which looks absolutely fine to me.One of the other answers, which i agree is correct and so does the mock exam is

b)
int [][] array2d = new int[2][2];

View Replies View Related

Swing/AWT/SWT :: Instantiation Of Listener Using Anonymous Inner Class

Jun 2, 2014

JMenuItem blueChoice = new JMenuItem("Blue");
blueChoice.addActionListener(new InnerMenuListener(){
public void actionPerformed(ActionEvent e){
String buttonCommandString = e.getActionCommand( );
if (buttonCommandString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonCommandString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonCommandString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else
System.out.println("Unexpected error.");
}
});

Can a method in an anonymous inner class ever be private? why or why not?

View Replies View Related

Declare And Concatenate Various Strings

May 27, 2015

Write a program that declares and concatenates various strings. Declare strings for your first name, middle initial and last name, along with one for your address, city, state and zip. Make an additional string called firstLine, which will be a concatenation of first name, space, middle initial, period, space, and last name. Assign each of these strings a value, and then print the information in the following format:

First Line (First name Middle initial (period) Last name)

Address

City, State

Zip

For example:

John Q. Public

1234 Any Street

Cleveland, Ohio

44101

Now reassign the strings in the same program (Do not create a separately compiled program!) and repeat the printout for different information. When you are finished, your program will print out two groups as above.

The information should be placed into the seven separate strings, then a first line should be formed by concatenating first name, space, middle initial, period, space, and last name. The city and state line should be formed by printing city followed by a comma, a space, then the state (NOT by concatenation). This is so you can see different ways of making lines."

And this is what I have so far:

View Replies View Related

JTable - Declare 2D Array

Jun 5, 2014

I have a jtable which i want to put an array into... and Really don't know how.. I dont want to use array list mainly because it looks way to complicated so there must be some other way using defaultablemodel but i dont know how..

So here's my code: just a snippet which includes the testing of the jtable

String[] columns = {"col1", "col2", "col3", "col4", "col5", "col6"};
//declare 2d array
String[] [] data = {{"1", "2", "3", "4", "5", "6"}};

jt = new JTable (data, columns);
jt.setPreferredScrollableViewportSize (new Dimension (50, 80));

//set initial selectibility to false
jt.setFocusable (false);
jt.setRowSelectionAllowed (false);

JScrollPane tableContainer = new JScrollPane (jt);
frame.getContentPane ().add (tableContainer);

View Replies View Related

How To Declare Array In Java

Apr 16, 2015

1.How to declare array in java?
2.How to push elements in it in key-value value pair in java?

For example-

This is the way i do it in javascript..
I want to do like this in java..

var my_array;
for(var i = 0; i<5; i++)
{
my_array.push({x: i, y:0});
}

where,push is builtin method in javascript.

View Replies View Related

Declare Two Dimensional Array In Java?

Oct 28, 2014

I want to declare a 2 dimensional array in java which has 3 column and unlimited number of rows, i want to give a special name to each column . The type of first column is string second one is int and the last one is string

Column1_name
Column2_name
Column3_name
String value
Int value
String value
.
.
.
.
.
.

View Replies View Related

Possible To Declare Two Data Input Stream?

Aug 3, 2014

I mean i need to access to two txt file at the same time so i did this in method:

DataInputStream din= new DataInputStream(FileInputStream("vip.txt"));

DataInputStream din2= new DataInputStream(FileInputStream("corporate.txt"));

But there are errors when i compile and they pointing to these two lines.

View Replies View Related

Declare Array And Populate It With Log Formula

Feb 10, 2014

Still trying to get a handle on arrays! So, I declare an array to be a 46x1 and I am trying to populate it with a Log formula that I am using but I keep getting an ArrayIndexOutofBoundsException.

Code :

private double[][] LNValues = new double[46][1];
//Calculating y=LN(E-k) and Initializing the Array
for(int x=0; x<LNValues.length; x++)
{
double i = Math.log(eValues[x][1] - kValue);
if(i > 0)

[Code] ....

View Replies View Related

Declare A Class That Can Be Used To Represent A Quadrilateral

Jul 16, 2014

2. Declare a class called Quadrilateral that can be used to represent a quadrilateral. What instance variables are required? This class should include the following methods:

• Accessor and mutator methods. Notice that negative and zero lengths should not be accepted.
• A method called isParallelogram that returns a Boolean value indicating if the quadrilateral is a parallelogram.
• A method called isRectangle that indicates if the quadrilateral is a rectangle. This method should invoke the method isParallelogram and return a Boolean value.
• A method called isSquare that returns the Boolean value “true” if the quadrilateral is a square. This method should invoke the method isRectangle and return a Boolean value. URL...

import java.awt.Point;
public class Quadrilateral{
private Point p1, p2, p3, p4;
public Quadrilateral (Point p1, Point p2, Point p3, Point p4) {

this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
}
}

that is all i got, my professor has never mentioned on anything about quadrilateral,and i have 0 knowledge about this.

View Replies View Related

Can Declare A Class Inside Interface?

May 8, 2013

I have a doubt regarding to java.

Can we declare a class inside an interface?

Ans :yes

But what will be the situation?

I am not getting why it is required...........

View Replies View Related

Make Program That Declare Largest And Smallest Out Of Three Numbers?

Jan 13, 2015

how can i make a program that declare the largest and smallest out of three numbers??

/*
* To change this license header, choose License Headers in Project Properties.
int a;
int b;
int c;

[Code]....

View Replies View Related

Is It Correct To Declare A Class Inside Main Method

Jan 21, 2014

I saw an example where an (inner)class is declared inside the main method, this is correct or not and why/when it's reasonable to use?so smth like this

public class myClass()
{
public static void myMethod(myInnerClass obj)
{
if (obj.method())

[code]....

View Replies View Related

Declare And Creates Integer Array That Can Hold 15 Integers

Nov 3, 2014

The main Method

-Create a main method declares and creates an integer array called nums that can hold 15 integers.

-Use a for loop to fill that array with multiples of 3: 0, 3, 6, 9, etc.

-Then use similar for loop to print each value in the array on one line, with each value separated by a single space.

-Compile and run the program to see the result:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

As you write other methods, you'll also modify the main method to make calls to them. The printArray MethodWrite a method called printArray that accepts an integer array as a parameter. This method does not return a value, and must be declared as static so that the main method can call it. Instead of printing the array in the main method, move that loop into this method. Call the printArray method from the main method. Compile and run the program to verify it prints the sam result as before.Add a println statement so that after printing the array values on one line, it then moves to the following line.Finally, modify the loop in the printArray method so that, instead of using a traditional for loop, it instead uses a for-each loop. Compile and run the program again.

Part III: More Array Methods

The linearSearch Method In lecture we looked at a method that performed a binary search on a sorted array. A much simpler (though much less efficient) search is a linear search, that simply starts at the front of the array and looks at each element in turn until it finds it or reaches the end.Create a method called linearSearch that accepts an integer array and a single int value as parameters. The goal of the method is to find the second parameter (the target) in the array. The method should return a single int representing the index of the target value. This method should not print any output itself. In this method, use a traditional for loop to scan through the elements in the array. As soon as you find the target value, return the index of that value.

If you scan through the entire array without finding the target value, return a -1.Modify the main method to call the linearSearch method and print the results. Call it twice, searching for the value 18 (which it should find) and the value 10 (which it should not). Including the previous activity, the output of the main method should now look similar to this:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sumArray Method

The sumArray method should take an integer array as a parameter and return a single integer representing the sum of all values in that array.Use a for-each loop to access each value in the array and compute a running sum. After the loop, return the total.Call the method from the main method, producing the following augmented output:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sum of this array is 315

The addValue Method...The addValue method should accept an integer array and a single int as parameters. The purpose of the method is to add the second parameter to EACH value in the array. The addValue method does not return a value, but the elements inside the array will be modified. Call the addValue method from the main method, adding 100 to each element in the array. Then call the printArray method again to see the modified array values:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sum of this array is 315 100 103 106 109 112 115 118 121 124 127 130 133 136 139 142

Test a Different Array..Finally, duplicate the content of the main method to perform similar tests on another array. Instead of filling it with multiples of 3, fill it with multiples of 4. And instead of using an array size of 15, use an array size of 20.Modify the values search for to include one that is in the array and one that isn't.Rerun the main method and carefully check the results.If you haven't been doing it all along (which you should), make sure the appropriate class and method documentation is included.When you're satisfied that all methods are working correctly, modify the main method to delete the second array tests.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved