Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped
Related
A few days ago I asked this question, and now I have a more specific one, since I worked on my program some more and added a few things. Basically I start out with an empty ArrayList which is supposed to hold birthdays that are added via console. This part I got down + it prints the birthday I add. But if I want to add another one, it prints the first one I added again? How could I make it print out all the birthdays I have added this far? I'll show the code I have so far
Birthday class
public class Birthday {
private String bdayKid;
private int age;
private boolean gift;
public Birthday(String bdayKid, int age, boolean gift) {
this.bdayKid = bdayKid;
this.age = age;
this.gift = gift;
}
//overridden toString() method
public String toString() {
return this.bdayKid + " turns " + this.age + "! They are" +
(this.gift ? "" : "not ") + " getting a gift.";
}
}
Main class
public class MainClass{
public static void main(String []args) {
ArrayList<Birthday> bdays = getBirthdays();
printBirthdays(bdays);
}
//This method will return a list of birthdays
public ArrayList<Birthday> getBirthdays() {
ArrayList<Birthday> bdays = new ArrayList<Birthday>();
Scanner scan = new Scanner(System.in);
//create a birthday
Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
//add the birthday to arraylist of birthdays
bdays.add(bday);
return bdays;
}
//This method will print a list of birthdays
public void printBirthdays(ArrayList<Birthday> bdays) {
//iterate through each birthday and print out the result
for (Birthday bday : bdays) {
System.out.println(bday);
}
}
}
and inside a long-ish switch statement i added this option:
System.out.println("Do you want to add another birthday?");
boolean anotherOne = scan.nextBoolean();
if (anotherOne == true) {
getBirthdays();
printBirthdays(bdays);
}
Do I need to add an if statement inside my for-each loop? Any help is appreciated!
You have a serious problem in understanding Java. First, you need to understand a concept, the scope of a variable.
If you create a variable inside a function, then the scope of the variable is in the function only.
You have different instances of ArrayList<Birthday> with the identifier bdays. One instance that you defined in void main function, and other instances are created each time you call getBirthdays() method. In the switch statement, when you call getBirthdays(), a new ArrayList<Birthday> is formed and returned by the function, while your original ArrayList<Birthday> bdays remains unchanged. And when you call printBirthdays(bdays) it takes argument as the array created by you in the first line of your main method instead of a new ArrayList returned by getBirthdays() method. Hence, it does not print the new Brithday. So, you can change your code something like follows:
Main class
public class MainClass{
public static void main(String []args) {
// Instantiate your one and only bdays array
ArrayList<Birthday> bdays = new ArrayList<Birthday>();
getBirthdays(bdays);
printBirthdays(bdays);
}
//This method will return a list of birthdays
public void getBirthdays(ArrayList<Birthday> bdays) {
Scanner scan = new Scanner(System.in);
//create a birthday
Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
//add the birthday to arraylist of birthdays
bdays.add(bday);
// Good practice to close a scanner
scan.close();
}
//This method will print a list of birthdays
public void printBirthdays(ArrayList<Birthday> bdays) {
//iterate through each birthday and print out the result
for (Birthday bday : bdays) {
System.out.println(bday);
}
}
}
and,
System.out.println("Do you want to add another birthday?");
boolean anotherOne = scan.nextBoolean();
if (anotherOne == true) {
getBirthdays(bdays);
printBirthdays(bdays);
}
Note that, Java passes objects as reference, so if you pass you **bdays** to getBirthdays(bdays) then every change inside this function done to bdays will also occur to your original bdays in main method. More precisely, they are the same ArrayList in your memory, and the variables bdays in two different methods main and getBirthdays(bdays) are just different identifiers referencing to same ArrayList<Birthday> that you created at the start of the function and passed as a reference to the getBirthdays method. Check other relevant tutorials on passing variables by reference in java.
IMO the best way to do this is splitting your getBirthdays() to printBirthdays() and addBirthday(). Here is the code and you can use your own logic to loop the input:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
static ArrayList<Birthday> bdays = new ArrayList<>();
public static void main(String []args) {
while(true) {
//Use this method every time you need to add new BDay
addBirthday();
//Use this method to print all BDays in ArrayList
printBirthdays();
}
}
public static void addBirthday(){
Scanner scan = new Scanner(System.in);
Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
bdays.add(bday);
}
public static void printBirthdays(){
for(Birthday b: bdays){
System.out.println(b);
}
}
}
Add field in the Birthday class:
private boolean printed = false;
Then on your print function:
//This method will print a list of birthdays
public void printBirthdays(ArrayList<Birthday> bdays) {
//iterate through each birthday and print out the result
for (Birthday bday : bdays) {
if(!bday.isPrinted())
{
System.out.println(bday);
bday.setPrinted(true);
}
}
}
my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}
import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
I want the user input from this class and
bring into another class and use the number variable for a
If statement
I want the user input from this class and bring into another class and
use the number variable for a If statement.
It is simple take a look at below example(make sure to add both classes in one package different java files as Player.java and ExampleClass.java),
This is the class that Scanner has:
import java.util.*;
public class Player{
public static void main (String [] args){
Scanner getInput = new Scanner(System.in);
System.out.print("Input a number");
//you can take input as integer if you want integer value by nextInt()
String number = getInput.nextLine();
ExampleClass obj = new ExampleClass(number);
obj.checkMethod();
}
}
This is the class that check number:
public class ExampleClass{
int number;
public ExampleClass(String number){
try{
//If you want to convert into int
this.number = Integer.parseInt(number);
}catch(NumberFormatException e){
System.out.println("Wrong input");
}
}
public void checkMethod(){
if(number > 5){
System.out.println("Number is greater.");
}else{
System.out.println("Number is lesser.");
}
}
}
Few thing to mention:
Your example code contains syntax errors, fix those first.
If you want integer you can use getInput.nextInt() rather than
getInput.nextLine().
You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
Use proper naming convention.
In my example I convert the String into integer inside the constructor and wrap with try-catch block to prevent from NumberFormatException(If you input character or something you can see wrong input will print). Sometimes in variaus situation it is not good to use try-catch in constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.
Where you normally make an import on the other class, just import the Player class and it should work
I'm not sure if I got it, I suppose you're using a scanner.
This is the way I would do that:
Scanner class:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insert a decimal:");
String inputValue = scanner.nextLine();
if(!new ScannerCalc().isNumeric(inputValue)){
System.out.println("it's not a number...");
break;
}
else
new ScannerCalc().checkNumber(inputValue);
}
}
}
ScannerCalc class:
public class ScannerCalc {
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
public void checkNumber(String number){
if(Integer.parseInt(number)%2==0)
System.out.println("it' even");
else
System.out.println("it's odd");
}
}
Pay attention on instantiation of classes to reuse methods.
If you want to make use of a local variable in another entity, it is better to pass it as an argument to a method of the other entity. For example
OtherClass.operation(scanner.nextLine()); // In case method is static
new OtherClass().operation(scanner.nextLine()); // In case method is not static
I need to return finalString value for input operator name.
where,internalPrestring is fixed for specific operator,internalDigit would be retrieved from getting operator name.then all of'em would be added to finalString.
but it is giving null, i can't understand the problem
import java.io.*;
import java.lang.*;
class CallManager
{
public static final String postString = "#";
StringBuilder stringBuilder;
String internalPreString;
String preString;
String middleString;
String finalString;
String operatorName;
int internalDigit;
//needs to set oprator name
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
//afeter having operator name need to set inrernal digit for each operator
public void setOperatorBasedInternalDigit(int getIntegerForOperator)
{
internalDigit = getIntegerForOperator;
System.out.println("I got it too " + internalDigit);
}
//it needs to get string from ocr
public void setString( String getMeFromOCR )
{
middleString = getMeFromOCR;
}
//preString creator for differnet operator
public String getOperatorBasedPreString(String operatorName)
{
if(operatorName.equals("Airtel"))
internalPreString = "787";
else if(operatorName.equals("Banglalink"))
internalPreString = "123";
else if(operatorName.equals("Grameen"))
internalPreString = "555";
else if(operatorName.equals("Robi"))
internalPreString = "111";
else if(operatorName.equals("TeleTalk"))
internalPreString = "151";
stringBuilder.append("*").append(internalPreString).append("*");
preString = stringBuilder.toString();
return preString;
}
//get operator name and retrive midlle string's digit size from it
public int getOperatorBasedInternalDigit( String operatorName)
{
if(operatorName.matches("^Airtel | Grameen | Robi$"))
internalDigit = 16;
else if(operatorName.matches("^Banglalink$"))
internalDigit = 14;
else if(operatorName.matches("^TeleTalk$"))
internalDigit = 13;
return internalDigit;
}
//check operator-based digit number with input middle string as a number then retrive final string
public String getString( String toBeInserted, int inetrnalDigit)
{
if(toBeInserted.length() == internalDigit)
{
int counter = 0;
char [] insertHere = new char[internalDigit];
for(int verifier = 0; verifier < internalDigit; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
break;
counter ++;
}
if(counter == internalDigit)
{
stringBuilder.append(preString).append(toBeInserted).append(postString);
finalString = stringBuilder.toString();
//to see what i've got finally as input for using this call manager method.it would be removed too
System.out.println(finalString);
return finalString;
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
}
//tester class that CallManager works rightly or not
class CallManagerDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name of Operator");
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
}
}
You are having only four lines that deals with your CallManager class:
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
The reason why you are getting null :
You are using a default constructor right and there processing is
done in it. So this is not a problem
Now on next line you call setOperator method which has this code:
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
Now here you are only setting thw variable operatorName and nothing else. So all other variables are null as you not doing any processing or something that will initialize them to something.
So when you print clm.internalPreString and clm.preString you get null as they are not initialized. But try printing clm.operatorName and it will print the operator name that you passed and was initialzed inside your method setOperatorName.
So as you have defined so many method inside your class, use them so that all the variables are set as per your logic
UPDATE
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
//call any methods for example and use the values returned from the method by storing it inside a variable
String mystring = getOperatorBasedPreString(String operatorName)
}
You have never set the values for the variables for those you are getting the NULL value.The terms get/set must be used where an attribute is accessed directly.Read Java Programming Style GuideLines For more clarity.Use appropriate getters and setter for getting and setting the value like you have done for operatorName.
Don't you think that you should call any of the function instead of the string variables using object.
You are just calling one function that is
public void setOperatorName(String getMeFromPreferences) {
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
You are calling default constructor with out any variable setting there,
You had not initialized any String you are calling form object.
I think you should call any of the function e-g
public int getOperatorBasedInternalDigit(String operatorName)
OR
public String getString(String toBeInserted, int inetrnalDigit)
Then you will get some string as you are expecting ...
Hope this will help you.
I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!