java,returning null value from method - java

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.

Related

how to return all of the content whilst adding it on as a string

import java.util.*;
public class Help {
public static String fromSender(ArrayList<Message> messageList, String pname){
for(int i=0; i<messageList.size(); i++){
if(messageList.get(i).getSender().equals(pname)){
pname = messageList.get(i).getContent() + " ";
}
}
return pname;
}
public static void main(String[] args){
ArrayList<Message> messageList= new ArrayList<Message>();
messageList.add(new Message("UKMark","UKJohn","message1 "));
messageList.add(new Message("John","Don","ah"));
messageList.add(new Message("UKMark","UKJohn","message2 "));
System.out.print(fromSender(messageList, "UKMark") );
}
}
I tried to test this code which is meant to print message1 message2 however it only prints message1, why does it do this when it goes through the whole array and storing it in pname
You overwrite the value in variable pname in your fromSender function by assigning it the first matched message's content in this line of code pname = messageList.get(i).getContent() + " ";. So in the rest of the loops, the pname is actually the first matched message content and no longer 'UKMark' so the second message's sender won't match.
Just use another variable to return from your fromSender function.
public static String fromSender(ArrayList<Message> messageList, String pname){
String result = "";
for(int i=0; i<messageList.size(); i++){
if(messageList.get(i).getSender().equals(pname)){
result += messageList.get(i).getContent() + " ";
}
}
return result;
}
Instead of =, use += inside your if statement. Issue will be resolved.
But ideally you should be using a separate String variable to maintain what you return, instead of using of the passed parameter, especially when it was supposed to meant something else than you are using it as.

How would I return this "clubName" array to ensure the "choice -1" is used

I wanted to pass the "result" of "You Chose : abc" to a return type, so I can then pass it into my serialized method, so that I can then serialize that chosen team. I know how to return an array, but how would I return an array -1 ?
Code snippets are as follows :
public class Display{
public String[] printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
System.out.println("You chose: " + clubName[choice - 1]); // return the clubName -1
}
return result; // how to declare return statement ?
}
}
Here is my serialize code, not sure how I would pass the array, via an alias or use object ?
public class Serialize
{
public void Serialize() // receive return type from printGreeting();
{
// how to put object info into files, rather than declare here ?
try
{
FileOutputStream fileOut = new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Any help with this would be greatly appreciated :)
Here you declare to return an array of String[]:
public String[] printGreeting(int choice, String[] clubName) {
// ↑ here you say this method MUST return an array if Strings
What you need is
assign the user's choice to returned variable
return just ONE String
public String printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
// assign choice to result
result = clubName[choice - 1];
// print choice
System.out.println("You chose: " + result); // return the clubName -1
}
// return the chosen club name
return result;
}
Actually, I don't know why result is a class attibute (but i cannot see declaration), what does not make much sense if you want to return it, I will code the method as:
public String printGreeting(int choice, String[] clubName) {
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // ??
if (choice >= 1 && choice <= 20) {
choice --; // if choice is valid, get the array position.
// print choice
System.out.println("You chose: " + clubName[choice]);
return clubName[choice];
}
// if the choice is not correct, return null or "" as you want
return null;
}
UPDATE
Could anyone advise how I would pass that returned String to my serialize method, I think I know how to serialize it, but not 100% sure on parameter passing.
I don't get exactly what you want to achieve, maybe would be better to rephrase question with your target clear, and your tries.
Serialize (shortly), in Java is make an object's attributes convertible to Strings, then, a String either an String[] array does not need to be serialized.
As long as Display methods are not static, you must create an instance of Display to execute as follow:
public class Main {
public static void main(String [] args) {
// create an instance of Display class
Display d = new Display();
// get the needed values to pass to printGreeting method:
String[] clubs = {"club one", "club two" // put 20 clubs
// get the index from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int choice = sc.nextInt();
// call the method and get the return:
String result = d.printGreeting(choice, clubs)
// then get a serializer and execute method:
Serialize s = new Serialize();
s.serialize(result);
}
}
change the method Serialize.serialize() to Serialize.serialize(String) as follows:
public class Serialize
{
public void serialize(String club)
// ↑ receive return type from printGreeting();
{
// your serialize code
}
}
What do you want to return? The club name (String) or the whole array?
It's not clear in your code if result is an array or a String, you simply say result = clubName. If it's an array it should be String[] result = clubName;, if you want to return a String it should be String result = clubName[choice -1];, in that case you have to change the method to public String printGreeting(int choice, String[] clubName) and you can return result;

How to pass a String value to another class in Java

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

Getting error on printing array

I got this code:
import java.util.*;
import java.io.*;
public class Oblig3A{
public static void main(String[]args){
OrdAnalyse O = new OrdAnalyse();
OrdAnalyse.analyseMet();
}
}
class OrdAnalyse {
public static void analyseMet() {
Scanner Inn = new Scanner(System.in);
try {
File skrivFil = new File("Opplysning.txt");
FileWriter fw= new FileWriter(skrivFil);
BufferedWriter bw = new BufferedWriter(fw);
Scanner lesFil = new Scanner("Alice.txt");
int i=0;
int totalOrd=0;
int antUnikeOrd=0;
String[] ordArray = new String[5000];
int[] antallOrd = new int[5000];
while(lesFil.hasNext()) {
String ord = lesFil.next().toLowerCase();
totalOrd++;
boolean ut=false;
int y=0;
int z=0;
for(i=0; i<ordArray.length; i++) {
if (ord.equals(ordArray[i])) {
antallOrd[i]++;
ordFraFor=true;
}
}
if(ordFraFor=false) {
antUnikeOrd++;
z=0;
boolean ordOpptelling=false;
while(ordOpptelling=false) {
if(ordArray[z] == null) {
ordArray[z] = ord;
antallOrd[z]++;
ordOpptelling=true;
}
z++;
}
}
}
System.out.println(ordArray);
}catch (Exception e){
System.out.print(e);
}
}
}
And this is supposed to do some heavy counting while reading the words out of a file one by one. However, when I finally try to print the array to terminal just check whether it is okay or not, before I start working on making the program able to write it to a text-file, it just gives an error which reads:
[Ljava.lang.String;#163de20
But I do not know how and where to check for errors in this case? Any help?
This is not an error... This is what the default toString() implementation of the Object class returns...
[Ljava.lang.String;#163de20
Means:
array of references ( [L )
of type String ( java.lang.String )
unique object ID
Code of Object.toString()
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
What you shouldd do is to use a proper way to print:
a loop
StringBuilder sb = new StringBuilder();
for(String s: myArray) {
sb.append(s);
if(sb.length()>0) {
sb.append(',');
}
}
System.println(s.toString());
Arrays.toString
Use Arrays.toString() to log your Array's contents
System.out.println(Arrays.toString(ordArray));
If you want a formatted output you need to iterate over it using a good old for loop.
for (int i = 0; i < ordArray.length; i++) {
System.out.printf("ordArray[%d] = %s", i, ordArray[i]);
}
Actually this is commonly considered to be a "mistake" of arrays in Java: arrays don't override toString(), sadly. What you see is Object's toString():
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
A common workaround is to use Arrays.toString():
System.out.println(Arrays.toString(oldArray));
You have to print the array element by element.
ie.
for(int i = 0; i < ordArray.length; i++)
System.out.println(ordArray[i]);

how to make more than condition in toString method

I want to list all names that end with "Reda" and ignore case sensitivity, I have tried the condition in the toString method at the bottom, but it would not print any thing.
public class Customer {
public static void main(String[] args) throws IOException {
File a = new File("customer.txt");
FileWriter v = new FileWriter(a);
BufferedWriter b = new BufferedWriter(v);
PrintWriter p = new PrintWriter(b);
human Iman = new human("Iman", 5000);
human Nour = new human("Nour", 3500);
human Redah = new human("Redah", 0);
human iman = new human("iman", 200);
human MohamedREDA = new human("MohamedREDA", 3000);
human Mohamed_Redah = new human("Mohamed Redah", 2000);
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
p.println(Iman);
p.println(Nour);
p.println(Redah);
p.println(iman);
p.println(MohamedREDA);
p.println(Mohamed_Redah);
p.flush();
}
}
class human {
public String name;
public double balance;
public human(String n, double b) {
this.balance = b;
this.name = n;
}
#Override
public String toString() {
if (name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))) {
return name + " " + balance;
} else
return " ";
}
}
Please avoid putting condition in toString method. Remove the condition there
public String toString() {
return name + " " + balance;
}
and change your logic in Customer class
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
for (int i = 0; i < h.length; i++) {
if (h[i].name.toLowerCase().endsWith("reda")) { // condition here
p.println(h[i]);
}
}
And make use of loops do not duplicate the lines of code.Every where you are manually writing the lines.
Check Java String class and use required methods to add condition.
String redahname = ("Redah").toLowerCase(); //put your h[0] instead of ("Redah")
if(name.endsWith("redah")){ //IMPORTANT TO BE IN LOWER CASE, (it is case insenitive this way)
//your code here if it ends with redag
System.out.println(redahname);
} //if it does not end with "redah" it wont out print it!
You can use this, but can you please explain your question more? What exactly do you need?
try this
#Override
public String toString() {
if (name.toLowerCase().endsWith("reda"))) {
return name + " " + balance;
} else
return " ";
}
String.equals() is not what you want as you're looking for strings which ends with "Reda" instead of those equal to "Reda". Using String.match or String.endsWith together with String.toLowerCase will do this for you. The following is the example of String.match:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
// the input to matches is a regular expression.
// . stands for any character, * stands for may repeating any times
// [Rr] stands for either R or r.
if (name.matches(".*[Rr][Ee][Dd][Aa]")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
and here is the solution using endsWith and toLowerCase:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
if (name.toLowerCase().endsWith("reda")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
You shouldn't put such condition in toString() method cause, it's not properly put business application logic in this method.
toString() is the string representation of an object.
What you can do, is putting the condition before calling the toString() , or making a helper method for this.
private boolean endsWithIgnoringCase(String other){
return this.name.toLowerCase().endsWith(other.toLowerCase());
}
None of your humans are called, ignoring case, Reda, so your observation of no names printed is the manifestation of properly working logic.
Your condition is redundant: you perform the same test twice:
name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))
If you need to match only the string ending, you should employ a regular expression:
name.matches("(?i).*reda")
toString is a general-purpose method defined for all objects. Using it the way you do, baking in the business logic for just one special use case, cannot be correct. You must rewrite the code so that toString uniformly returns a string representation of the object.

Categories