Creating New Objects Within Methods?
Sep 14, 2014
I want to make a program where users are prompted to enter a username and a password and have these two values create a new instance of the Object User. But I'm not sure where to start.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
createUser();
[Code] ....
how to take username + password and put it into an object.
View Replies
ADVERTISEMENT
Mar 20, 2014
public class demo
{
Public class static void main(String[]args) {
//Creating a variable that will be a reference to the object
Peoples person_one;
[Code] ....
I have assembled this code below that has a void method which will creat a new object. Problem I encounter is that in
Create_object(person_one);
the person_one has an error saying not initialized. I'm jus trying to learn on my own ways here and practice so may know what's wrong with this? I know I can use a return object from methods but what about this approach?
View Replies
View Related
Dec 30, 2014
I'm trying to create complex Character objects. Each object has a name, and for each object with the same name, they share some of the same initial data. However, there are also some bits of data that are given to the object when it's created. For example, an "Elephant" always starts out having a weight of 500, but its position is determined when it's created. Any of these values may later be changed during runtime.
class CharacterStaticParameters {
int weight;
int numberOfFeet;
int numberOfEyes;
[code]....
For example, whether I should try to use words other than 'static' and 'dynamic', or a nicer word than 'parameters'?
View Replies
View Related
Aug 17, 2014
So I'm still trying to get to grips with Java, and like to understand exactly why I'm doing something, so that I am not just regurgitating the code, If I want to create an object from class "Apples", I would use the following, right?
Apples MyAppleObject = new Apples();
From what I understand, MyAppleObject is the new object name, new -> creates a new instance of it in memory, and Apples() is the onCreate method that is called
So question 1: (just a quick aside question) Can I create an object without calling Apples()? i.e.
Apples MyAppleObject = new;
Question 2: - PARTLY SOLVED - I discovered that (Button) is a way of typecasting, so I understand that line a little better. What I don't understand is why we don't need to initialize the object with "new"
I've now looked at a bit of android development and xml and those declarations are all together different, and I'm not sure why. I haven't found a single explanation for the difference in format.
Java Code:
Button Add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.button1); mh_sh_highlight_all('java'); So the Button object is declared above the onCreate method, but initialized afterwards I guess....
But instead of using Button Add = new Button() they use Add = (Button) findViewById(R.id.button1);
Question 3:
then In XML they use the following:
Java Code:
public*static*void*main(String[] args){
*********
********// Creates a DOM object in memory. Now you can access
********// data in the xml file
*********
********Document xmlDoc = getDocument("./src/tvshows5.xml"); mh_sh_highlight_all('java');
Once again, why didn't they have to use : Document xmlDoc = new Document()
View Replies
View Related
Jun 13, 2014
Java Code:
class GenericQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void push(E element) {
list.addFirst(element);
}
public E pull() {
return list.removeLast();
[code]...
Is a constructor required to create an object, if one of its instance or class variables haven't been instantiated? Like private String string;
View Replies
View Related
Mar 16, 2014
I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.
I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.
here is my contacts class
public class Contact
{
String name;
int number;
[Code].....
In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?
View Replies
View Related
Jul 21, 2014
So I have this class containing all my Enum types, also including methods for fetching Enum types based on their title attribute:
abstract class Enums {
static private Landmass getLandmass(String name) {
for ( Landmass l : Landmass.values( ) ) {
if(l.title.equals(name)){
return l;
[Code] .....
The second method (getAttribute) is created by copy-paste and I also need to repeat this exercise with several other types of Enums. This seems like a waste of code however.
Instead, I thought I'd create a generic method for fetching any type of Enums. As far as I could follow the tutorial @ Oracle I need a generic class for this. Thus the EnumHelper class:
abstract class EnumHelper<T> {
private T getEnum(T type, String name) {
for ( type t : type.values( ) ) {
if(t.title.equals(name)){
return t;
}
}
return null;
}
}
This, however, doesn't compute:
horoscopeEnums.java:234: error: cannot find symbol
for ( type t : type.values( ) ) {
^
symbol: class type
location: class EnumHelper<T>
where T is a type-variable:
[Code] ....
2 errors
To be honest I haven't been able to make much sense of the documentation on generics, thus its no surprise I'm stuck.
View Replies
View Related
Dec 14, 2014
I have two classes, MonsterGame (shown below) and Monster. Monster has a public accessor method to get it's private character variable, which represents the first character of the name of the Monster in question.
I'm just a bit confused as to why am I unable to cycle through the array of Monsters I have in the MonsterGame class and call
m.getCharacter(); (pretty much the last line of code)
public class MonsterGame{
private static final char EMPTY_SQUARE = ' ';
private char[][] gameBoard = new char[10][10];
private Monster[] monsters = new Monster[4];
private int maxXBoardSize = gameBoard.length -1;
private int maxYBoardSize = gameBoard[0].length -1;
[Code] ....
I understand that there need to be instances of objects to call methods, but is that not the case here? the Monster objects are have already been created, no? Do I need to create an index for the array? is the for loop not enough?
View Replies
View Related
Jul 27, 2014
I'm trying to create a simple bar chart from integer values (measuring number of bulldozers) stored in a mySql DB, in the following schema:
Integer rigId PK;
Integer rigQty;
Date recordDate;
String country FK;
I want to plot the date on the x-axis and quantity on y-axis. I can't seem to find any examples of how to render charts from a database. I just find the generic Primefaces 4.0 examples which uses static data like this:
private void createCategoryModel() { // category chart
categoryModel = new CartesianChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Boys");
[Code] ....
I'm really not sure how to adapt the above to a database method nor have any web searches produced useful examples. I tried something like this, but how to find examples or the type of methods I need to use to create a bar graph from Db values:
@ManagedBean(name = "chartb")
@SessionScoped
public class BarChartBean {
private final Map<Integer, Map<String, Number>> rigNums = new HashMap<>();
// private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>();
private CartesianChartModel cartesianChartModel;
[Code] ....
View Replies
View Related
May 25, 2014
I've been trying to write a program for some time now, but im encountering problems while trying to complete it. The program has a student class and a course class (set up with some info about the class, like #, professor name, course title, course time). Now, i have a text file in the workspace, and i have to import the data from the textfile, and thats just what i did, but then there is an option which allows the user to delete a course only by inputing the course number, and when he does that, the program outputs the course's name, and confirms the deletion of the course (From the student's record, i created a vector for that and imported all the courses from the text file). But how can i let the program know what's the name of the course when the user inputs the course number ???
When the data is read from the file, objects should be created and added to the student's course record. <- i think here's where i messed up ? i imported the data, but how can i actually make them objects before adding them into the vector ?
PHP Code:
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
Vector Record = new Vector();
try {FileReader filereader = new FileReader("CLASSES.txt");
BufferedReader bufferedreader = new BufferedReader(filereader);
String test = "";
while(test != null)
{
Record.addElement(test);
test = bufferedreader.readLine();
} mh_sh_highlight_all('php');
View Replies
View Related
Jul 14, 2014
I thought you can only create a new object using private implementations and then using a constructor to set your arguments inside the parameters of the constructor to the instance variables but how come he created an object without any private implementations and just methods inside the constructor.
import javax.swing.JFrame;
public class MyWindow extends JFrame {
public static void main(String[]args){
new MyWindow();
}
public MyWindow(){
setSize(500,500);
setVisible(true);
setTitle("MyWindow");
}
}
View Replies
View Related
Sep 27, 2014
I am trying to get the average of 3 different fraction arrays. I made a fraction class and I made methods such as read() and average() in this new class.
package fractions;
import java.util.Scanner;
import java.util.Arrays;
public class FractionArrays {
public static void main(String[] args) {
Fraction completeFraction = new Fraction(5,6);
[Code] ....
I was wondering if there was any way to use the arrays I created in the read method in the average method. If I find that out I should be able to do it on my own. Is there a way to make the arrays public to use in different methods?
View Replies
View Related
May 5, 2014
Okay, so I have to create a class with instance data and instance methods.
First, BankAccount class. It should contain the following information, stored in instance variables:
First name: The customer's first name.
Last name: The customer's last name
Balance: The amount of money the customer has in the account.
It should have the following methods:
BankAccount(String firstName, String lastName,
double openingBalance)
This constructor creates a new BankAccount
public String firstName()
Returns the customer's first name
public String lastName()
Returns the customer's last name
public double balance()
Returns the customer's account balance
Finally I need to create a driver to test my class. And create several accounts and verify that the first name, last name, and balance methods work properly. This is my code below.. I don't know if I did it right.
public class BankAccount {
String firstName, lastName;
double balance;
public BankAccount(String firstName, String lastName, double balance) {
[Code] .....
View Replies
View Related
Nov 26, 2014
I'm working on a project that involves the following:
-Creating a superclass of bankaccounts
-Creating two subclasses, checkingaccount and savingaccount
-Each of the two subclasses has different methods (writeCheck for checking, for example)
-Both types are created in a main class bank and stored in the same array
So let's say a user goes through the menus and creates a few savingAccounts and a few checkingAccounts (stored in the accounts[] array). Then, to write a check from one account, the user can enter the account number (a string), and the method will use a for loop to cycle through the array until it hits an account number match. Then it checks that it's the correct account type and calls methods from the subclass.
Problem here is that some methods work and some don't. In the following example:
for (BankAccount account: accounts) {
if (account.getAccountType().equals("Checking")) {
do {
if (account.getAccountNumber().equals(accountNumber)) {
amount = Double.parseDouble(JOptionPane.showInputDialog(
[Code] .....
The getAccountNumber method works but writeCheck is throwing an error. I tried creating a method in the superclass and overriding it in the subclasses but with no success.
View Replies
View Related
Aug 20, 2014
What is the best choice to program like an applet i mean easy with creating multithreading or drawing objects etc.
View Replies
View Related
Oct 7, 2014
This is titled "Creating static methods that accepts arguments and returns a value". I think that I understood everything about this except for the very bottom part of the code. I wasn't really sure where to put it. From the errors that I am seeing, I know which line is giving the errors but I'm not sure what is wrong with it.
import java.util.Scanner;
public class ParadiseInfo2{
public static void main(String[] args){
double price;
double discount;
[Code] ....
Errors:G:ParadiseInfo2.java:29: error: illegal start of expression
public static double computeDiscountInfo(double pr, double dscnt)
^
G:ParadiseInfo2.java:29: error: illegal start of expression
public static double computeDiscountInfo(double pr, double dscnt)
[Code] ....
6 errors
Tool completed with exit code 1
View Replies
View Related
Nov 22, 2014
I was doing a project in a usual Java Application, but now maybe I have to use some tools that are contained in javafx.scene.media.MediaPlayer so I wonder if can it all work? Will javafx methods and such works?
I have to use javafx.scene.media.MediaPlayer beacuse I have to create a very simple audio player (one jbutton and one jcombobox).
View Replies
View Related
Jun 8, 2014
in my progrm there are three diff array of objects...namely garments..gadgets and home app...now one who buys from each of these sections will have to make a bill at last...when he choses to make the bill he will be shown the list of products he bought and their details (like price...brand...etc)...so i thought that while he orders each product(which is done in a previous method called purchase()...)....(each product is stored as an object in there diif arrays namely garments...gadgets ...appliances)....each of those object will be copied in a new array in a diif class...then that array print will give me the desired result...
is this approach correct...?and if its correct then how can i pull out a specific obj frm a stored array of object and then save it in a new array....?
View Replies
View Related
Apr 25, 2014
We're learning how to use Binary I/O commands...which equates to....
My issue is trying to relate the Fraction objects (which we are to create using a loop) with the read/write methods used in Binary I/O (input/output streams). I left a blank after the output.write(), so you can see where the issue exist.
Java Code:
import java.io.*;
public class FractionTest {
public static void main(String[] args) {
int [] fraction = new int[3];
for(int i = 0; i <= fraction.length; i++){
Fraction numbers = new Fraction();
[Code] ....
View Replies
View Related
Dec 10, 2014
This program is basically complete. It compiles and runs. It is a college course assignment that I pretty much completed but for the last part in which I'm suppose to change the values of all fields and display the modified values using a toString method. Modifying the values of the fields is where I am stuck. I don't think I need to create a new text data file to do this. The instructor only asked that all the values of fields be changed and this was the last part of the assignment so I don't think it involves creating additional ObjectOutputStream and ObjectInputStream objects. I'm getting a NullPointerException error on line 161.Here is the code. I'm also including the input data file.
//create program so that objects of class can be serialized, implements interface Serialiable
//create constructor with 4 parameters with accompanying get and set methods, Override toString method
//create text file with 5 records, create Scanner object,ObjectOutputStream, and ObjectInputStream
//create new ItemRecord object, change values of all fields in ItemRecord object using object's set methods
//modify ItemRecord object using toString method
[hightlight =Java]import java.io.Serializable;
public class ItemRecord implements Serializable
[Code] .....
This is the error message:
----jGRASP exec: java ItemRecordReport
Item Cost Quantity Description
Number
A100 $ 99.99 10 Canon PowerShot-135
A200 $149.99 50 Panasonic-Lumix T55
A300 $349.99 20 Nikon- D3200 DSRL
A400 $280.99 30 Sony- DSC-W800
A500 $ 97.99 20 Samsung- WB35F
Exception in thread "main" java.lang.NullPointerException
at ItemRecordReport.main(ItemRecordReport.java:161)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is the data file:
A100 99.99 10 Canon PowerShot-135
A200 149.99 50 Panasonic-Lumix T55
A300 349.99 20 Nikon- D3200 DSRL
A400 280.99 30 Sony- DSC-W800
A500 97.99 20 Samsung- WB35F
Here is the data file for the modified field values.
B100 98.00 10 ABC1010
B200 97.00 15 DEF1020
B300 96.00 10 GHI1030
B400 95.00 05 JKL1040
B500 94.00 01 MNO1050
View Replies
View Related
Mar 5, 2015
How do you declare methods for a class within the class whilst objects of the class are declared else where?
Say for instance, I have a main class Wall, and another class called Clock, and because they are both GUI based, I want to put a Clock on the Wall, so I have declared an instance object of Clock in the Wall class (Wall extends JFrame, and Clock extends JPanel).
I now want to have methods such as setClock, resetClock in the Clock class, but im having trouble in being able to refer to the Clock object thats been declared in the Wall class.
Is this possible? Or am I trying to do something thats not possible? Or maybe I've missed something really obvious?
View Replies
View Related
Jul 27, 2014
I am currently working on a project where I need to return data from a database over RMI to a client who requests it. Some of the fields in the Data Object can not be seen by the client so I need to create another object to send over the network instead. The method I use is this...
public static SerializableObject createSerializableObjectFromDataObject(DataObject dataObject){
SerializableObject serializableObject = new SerializableObject();
serializableObject.setField(dataObject.getField());
serializableObject.setAnotherField(dataObject.getAnotherField());
return serializableObject;
}
Is there a better way of doing this? I am creating many subclasses DataObject which all require this static method to be implemented and I can't push it into the superclass because each one needs custom behaviour.
View Replies
View Related
Jan 23, 2015
how String objects are different from other objects
part 1:
// creating two objects
Dog mydog1 = new Dog();
Dog mydog2 = new Dog();
// comparing the reference variables
if( mydog1 == mydog2){
System.out.println(" The reference variables refer the same object ");
}
else {
System.out.println(" They refer to different objects ");
}
The above code works as I understand objects , it prints "They refer to different objects " to the screen.
Part - 2
// creating two objects ( I beleive, pls correct me if i am wrong )
String a = "haai";
String b = "haai";
if( a == b){
System.out.println(" Reference variables refer to same object");
When i run the above code it prints that a and b refer same object , I don't understand how they refer to same object when i didn't assign " String b = a; ". My question is did java just create one object and stored the same reference values to a and b .
View Replies
View Related
Jan 10, 2014
I have written two methods called "contains" and "overlaps". The method "contains" is to detemine whether a point (x, y coordinate) is within the surface area of a square object. The location of the square objects is determined by the location of the upper left corner of the square.The method "overlaps" is to determine whether two square objects overlap each other.
I have written these as two separate methods. However I want to change the method "overlaps", so that it uses the method "contains" within it. I.e. using a method within a method. Thereby hopefully making the "overlaps" method a bit more clear and easy to read.
Java Code:
/** Returns true of the point with the coordinates x,y, are within the square. */
public boolean contains(int x, int y){
int sx = location.getX(); //"location" refers to a square object
int sy = location.getY(); // getX() and getY() are to find it's coordinates
// "side" is the side length of the square
if (x >= sx && x <= (sx + side) && y >= sy && y <= (sy + side)){
[code]....
View Replies
View Related
Jun 8, 2014
Im creating a program that has about 20 different input forms. Fairly standard forms but what i need to know whats the easiest way of creating forms. Is there some way of using templates or some plugin to quickly generate forms.
View Replies
View Related
Feb 6, 2015
I am having trouble developing a 4x4 grid that has the letters A-Z and a-z and the corresponding ASCII numbers for each letter. I have created the code to retrieve these letters and their corresponding ASCII numbers, I only am having trouble with creating the grid and displaying these numbers and letters in their separate 4x4 grids: one grid for (a-z), one grid for (A-Z), one grid for (ASCII# a-z), one grid for (ASCII# A-Z).
Java Code: // Constants Declaration Section
//*******************************
public static void main(String[] args)
{
// Variables Declaration Section
//******************************
[code]...
View Replies
View Related