Private Method For Changing String Instance

Feb 12, 2015

I want to make a private method that will change the value of a instance variable like this:

String bla = "bla bla bla";
private void changeString (String x) { x = "eee";}
changeString(bla);

Now value of the variable bla should be "eee" but its not, it is stil "bla bla bla".

View Replies


ADVERTISEMENT

Object / Methods - Private Instance Variables

Jun 30, 2014

so, i was reading my java book and learning about objects and methods and it starts talking about Encapsulation and mentions that it's good practice to set instance variables as private and instead of accessing the instance variables directly, we should create a set method and get method to get and set the stuff we want to pass to the class containing the object...

for example, in this class, we're passing the integer 70 for object dog one and integer 8 for object dog two for the dog class... and these these 2 integers are sent to the setsize method so we're not accessing instance variable size directly.

i dont quite get it though....if we the programmer are the one deciding what size the integer is for the dog, and the setsize method takes the one.setSize(70) or (8) and puts them in setsize(int s) as s... but only to copy that integer stored in s back to private int size.... why do we even need to bother with making these two extra methods such as setSize, getSize?

in the book it says that... well what if the code gets into the wrong hand and someone writes something like one.setSize(0) then you would get a dog with size 0 which is essentially illogical. but then again, i'm the programmer, and i am the person who writes the code and passing the right integer.The reason for public and private... that part i understand... i can see why if a variable's data can get changed amidst the code during calculations and you dont want it to directly change the original variable and have it mess up the code, but this code from the book just a bad example of demonstrating the reason? since we manually pass the information ourselves and passing it to method setSize... and all setSize does is stores it in another integer, only to copy it right away to size (which is the original private variable we were tryign to protect?

Any simple code to demonstrate how the code might end up changing an instance variable and why we would want to protect it by using private?

class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;

[code]...

View Replies View Related

Changing Value Of Object Instance

Jul 13, 2014

I have been working on a program that is meant to use a class' instructions in a program to add a value to a variable, save it, and present it. This is my class

public class Car
{
//FIELDS
private int yearModel;
private String make;
private int speed;
//METHODS
public Car(int carYearModel, String carMake)

[Code] .....

Whenever I call the accelerate method, a value of 5 is to be added to the speed variable. But whenever I call accelerate, it doesn't increase! I just don't understand why not. I've tried different renditions of adding 5 to speed and it doesn't quite work. I don't get any errors when I compile, just runtime, when it doesn't add 5 to speed.

View Replies View Related

Calling Private Method To Another Method Located In Same Class

Oct 23, 2014

I am trying to call a private method to another method that are located in the same class.

I am trying to call prepareString to the encode method below.

Java Code:

public class ShiftEncoderDecoder
private String prepareString(String plainText)
{
String preparedString = "";
for(int i = 0 ; i < plainText.length();i++)
if(Character.isAlphabetic(plainText.charAt(i)))

[Code] .....

View Replies View Related

Mockito / Powermock Private Void Method

Jul 29, 2014

I need to mock a private void method which takes no arguments using mockito and powermock.

The method belongs to a instance which is a spy.

I am working with an old project converting the unit tests from one testing framework to another.

View Replies View Related

String Class Private Final Character Length

Feb 27, 2015

The String class stores the characters of the string internally as a private char[] and calling someString.length() results in getting the length field from the character array. I am looking to get the details on how the length is implemented. I understand it is a field, but in the original question I provide sample code and really want to know if/how the resulting byte code may differ when compiled, perhaps I am just not seeing the simple answer through my confusion.

Link ....

View Replies View Related

Changing String To Int - Returning Unwanted 0

Oct 17, 2014

public class Lab07 {
public static void main (String[] args) {
System.out.println(convertToInt("123"));
} public static int convertToInt(String str) {
int conversion = 0;
int i;

[Code] ....

The only methods I am aloud to use is length and charAt, which I have done. I see why it is returning a 0 at the end of the value returned, its because I set my int conversion = 0. If I just declare it I get a compiler error that it must be initialized.

View Replies View Related

Error In Code While Changing String To Int Array

Mar 7, 2015

import java.io.InputStreamReader;
import java.util.Scanner;
public class FinalCombinations {
public static void main(String[] args){
//Read number of values
System.out.println("Enter the no of values");

[Code] .....

I am getting output like this

Enter the no of values
4

Enter the values
1
2
3
4

Enter the number for combination
2
C(4,2)=6
1
1
2
1
1
3
1
1
4
2
2
3
2
2
4
3
3
4

where as I want output like this..wit one array
1
2
1
3
1
4
2
3
2
4
3
4

View Replies View Related

How To Pass Object Type To A Method / Then Create Instance

Aug 9, 2014

Essentially, the code I want is:

public void randomCreate(ParentObject obj){
int x = random(0-4); //pseudo
int y = random(0-4); //pseudo
create new ParentObj(x,y);
}

ParentObject is actually abstract, so you would only ever pass one of its children objects to it, and a child object of that type would be created. It seems like there should be a way to pass a type, rather than an object, and then create an instance later down, but I don't know if that is actually possible, or if it is poor programming style.

View Replies View Related

How To Write Instance Method For Rectangle Class Called Contains

May 29, 2014

Write an instance method, contains, that has one explicit parameter of type Rectangle. The method should return true if every point of the rectangle determined by the explicit parameter is on or within the rectangle determined by the implicit parameter. It should return false otherwise.

This is what i did so far?

public boolean contains(Rectangle other) {
Rectangle intersect = Rectangle.intersection(this, other);
if ((intersect.left == this.left) && (intersect.bottom == this.bottom) && (intersect.width == this.width)
&& (intersect.height == this.height)) {
return true;
} else {
return false;
}
}

View Replies View Related

Writing IndexOf Method For More Than One Instance In A Linked List

Jun 7, 2014

I'm trying to write an indexOf() method that will return every time a value occurs in a linked list. I need to use my user-created linked list not the built in Java linked list. For example in a linked list of characters: "i, p, z, z, n, d, p, z" when I search for "z" it should return position variables for 3, 4, and 8. Currently what I have is obviously only returning the first instance.how I can return more than one instance?

public int indexOf(char input) {
LLNode currentNode = this.first;
int position =1;
boolean found = false;

[code]...

View Replies View Related

Performing Method On Instance Inside Abstract Class

Mar 12, 2015

How do I create an instance of a class in a method?

I am a bit rusty whenever I think of instances. I always think of main method and objects when I see instance which gets me confused on what to do when I am not in a main method. The example:

I have a abstract class, School, and inside School I have some methods that must preform some action on an instance. For example, there is a move() method that must move the instance of School. Another method named, personOld(), which returns whether or not an instance of School surpassed some determined age.

How do I do this and create this instance?

View Replies View Related

Changing Boolean Method Based On Result

Sep 20, 2014

I am working on a program that simulates someone logging in. For this program, I have three methods:

public void input(String text)
public void click(String button)
public boolean loggedIn()

Naturally, the default status of loggedIn() is false, but I am having trouble changing the boolean to true when a user has successfully entered a username and password.

Specifically,

public void click(String button) {
Button = button;//Button is declared at the beginning of the class
if(Button == "Submit") {
//Statement that changes loggedIn() from false to true when the user clicks the "Submit" button.
}

No matter what I try, I get various errors about how what I tried was illegal.

View Replies View Related

Method That Return Instance Of A Class That Implement Iterator Interface

Apr 14, 2015

I have been researching the Iterator and making a class implement iterable. I have seen this example shown below and was wondering how I could change this so that iterable() is not called upon in the main. I would like to be able to make a method that returns an instance of a class that implements the Iterator interface hopefully an inner class. This is because my program will not have a main and will be supplied with a main that includes a new Object with will use the iterator method.

import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");

[Code] ....

This is all I have been able to understand from what I want to do. This does not work and this is what I am trying to achieve

public class MyArrayList implements Iterable {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
 
[Code] ...

View Replies View Related

Converting Parent Instance To Child Instance?

Mar 7, 2014

I've Parent and child(extends Parent) class To initialize the constructors, I'm injecting from google.juice#injector. Let me show the code,

Parent.class

public class Parent{
private Animal animal;
@inject
Parent(Animal animal){
this.animal = animal;

[code].....

When I do this, ClassCastException is happening. Why is it so? Is there any way to convert instance of parent to child instance.

View Replies View Related

Method Creation - Take A String With Duplicate Letters And Return Same String Without Duplicates

Nov 7, 2014

How can I write a method that takes a string with duplicates letters and returns the same string which does not contain duplicates. For example, if you pass it radar, it will return rad. Also i would like to know how can I Write a method that takes as parameters the secret word and the good guesses and returns a string that is the secretword but has dashes in the places where the player has not yet guessed that letter. For example, if the secret word is radar and the player has already guessed the good guesses letters r and d, the method will return r-d-r.

View Replies View Related

String Split Method To Tokenize String Of Characters Inputted?

Sep 27, 2014

I am currently trying to make a calculator in Java. I want to use the String split method to tokenize the string of characters inputted. I thought I was using the String split method wrongly, because I had surrounded the characters I wanted to delimit with square brackets. However, when I removed the square brackets, the code threw an exception when I pressed the equal button. The exception was a PatternSyntaxException exception. Am I using the String split method wrongly? And why is the exception thrown? Here is my code:

import javax.swing.*;//import the packages needed for gui
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.List;
import static java.lang.Math.*;
public class CalculatorCopy {
public static void main(String[] args) {

[Code] .....

View Replies View Related

Class Method Which Take String And Returns A String In Reversed Version

Dec 16, 2014

i am trying to write a class method which will take in a string and returns a string which is the reversed version of that string. it compiles fine but when i try to run it it states Main method not found in class StringReverse,please define the main method as public static void main(String[]args). I am new to java and cannot figure out

import javax.swing.JOptionPane;
public class StringReverse {
public String reverseString(String str){
JOptionPane.showInputDialog(null,"Please enter word");
char c = str.charAt(str.length()-1);
if(str.length() == 1) return Character.toString(c);
return c + reverseString(str.substring(0,str.length()-1));}}

View Replies View Related

Accepting String And String Array In Just ONE Method?

Mar 18, 2014

Code a Java method that accepts a String array and a String. The method should return true if the string can be found as an element of the array and false otherwise. Test your method by calling it from the main method which supplies its two parameters (no user input required). Use an array initialiser list to initialise the array you pass. Test thoroughly.

public class test {
public static void main(String[] args) {
Printhelloworld();
String[] verbs = {"go", "do", "some", "homework"};
printArrays(verbs);

[Code] .....

View Replies View Related

String Split Method To String Array

Sep 21, 2014

So I'm creating a class which when given three inputs uses them as sides of a triangle and tells ther user what type of triangle it is, or if the input is invalid, tells them why it is invalid. I'm readin the input as a string and then trying to split it into a string array, from there checking to see if it has 3 elements.. in which the data is good at that point, and then converting them to ints and checking to see if they're negative ansd finally checking to see if they can work as sides of a triangle ie a+b >c, a+c >b , b+c >a.

I'm trying to split it into an array of strings but am getting an error, and can't seem to figure out why as this should be working from what I've read of the string.split method online.

import java.util.*;
public class TriangleTest{
private int sideA;
private int sideB;
private int sideC;
public static void main(String[] args){
TriangleTest triangle = new TriangleTest("3 4 5");

[Code] ....

The output reads [Ljava.lang.String;@15db9742

View Replies View Related

String Not Being Passed Into Method?

Oct 20, 2014

The only problem I am having is I cannot get my string plainText to go through the encode and prepareString methods.

Is there something in my methods that is wrong, or is it the way that I am calling them?

What is happening is if I enter "this is a test" as a plainText I am getting the samething back with no changes.

View Replies View Related

Sort String Method

Aug 7, 2014

I am getting incombatable types, I do not know why I am getting them..why I am getting the error?

The Error I am getting:
stringSort.java:26: error: incompatible types
if(myArray[j].compareToIgnoreCase(myArray[i].toString())){
^
required: boolean
found: int
*/

[code]....

View Replies View Related

Calling A String To Another Method

Oct 23, 2014

I need to get the string encodedString from the method encode able to be used in the decode method.

Java Code:

public String encode(String plainText) {
int prepareString;
int shiftChar;
String preparedString2 = prepareString(plainText);
String encodedString = "";
for(int c = 0 ; c < preparedString2.length();c++)

[Code] ....

View Replies View Related

String Intern Method

Oct 15, 2014

I understand that the intern() method is to be used when you create Strings using the new operator and you want the 2 strings to be the same object. But in that case, why can't we just enclose the 2 strings in double quotes instead of using the new operator

View Replies View Related

What Does Static Private Actually Mean

Mar 19, 2015

So I'd like to know what all the statement, not sure if it's the correct way of calling them but I'd like to know what like all of those purple-ish colored words in eclipse actually mean.Here's what I know so far, so if you can add some stuff to it or just correct me:

public - can be accessed by different classes.
private - can't be accessed by different classes.
static - adds a '.' which pretty much lets you like use methods on it? Not really sure about this one.
final - a final value of a variable meaning it couldn't and willn't change?
super - I have no clue, maybe something that has to be executed first? Not sure.
void - bassicly you don't have to use return as it doesn't return any value.
this - Uh-.. I think it has something to do with the class this keyword has been entered into, not quite sure what it does though.

I assume there are alot more but I am just not sure about these common ones, what the actually do and what's their purpose?

View Replies View Related

Using Main As Private?

Mar 25, 2014

What happened when we use main() as a private. . . . .???????

View Replies View Related







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