Storing an array of formatted names in JAVA? - java

I'm having trouble with my assignment and I've been scratching my head at it for a long time now. This is the criteria--
Your EmployeeNames class needs to have a static method named convertName().
The method should accept an array of last names as the input parameter.
The method should return an array of formatted names(first and middle initials and last name).
For each element, it should determine the first initial and middle initial of the name and format it correctly (ex, H. T. Smith)
It should store each of these formatted names as elements in a formatted names array.
After processing all the names, the method should return the formatted names array back to the calling program.
This is my code:
public class EmployeeNames {
String[] names;
public static String convertName(String names) {
for (int i=0; i<10; i++) {
names[i] = names.substring(names[i].length - 2, names[i].length);
}
return names;
}
}
It's not even working right now, as I'm receiving the 'array required, but java.lang.String found' error. But even after that, I'm not sure what to do. Can anyone help?

After processing all the names, the method should return the formatted
names array back to the calling program.
You'll have to change the method to return String[] instead of String.
public static String[] convertName(String[] nameString) { ... }
^
|
/* Note: I have changed it to avoid any confusions */
You'll also have to make names as static,
private static String[] names;
Edit: Thanks, #Mark for pointing out that method should also accept String[] instead of a single String object.

The issue
I'm receiving the 'array required, but java.lang.String found' error.
You have a global variable called names but also a variable called names in your method parameters.
Because they have the same name, names in your method parameters is hiding the global variable names. Since your method parameter names is declared as String instead of String[] it's throwing that error.
The fix
To solve your issue, remove the global names and change the parameter names from String to String[].
After which you'll notice that you should also change:
The return type from String to String[]
names.substring to names[i].substring
names[i].length to names[i].length() since that's the length method for String.
Changed code
The code after the changes:
public class EmployeeNames {
public static String[] convertName(String[] names) {
for (int i = 0; i < 10; i++) {
names[i] = names[i].substring(names[i].length() - 2, names[i].length());
}
return names;
}
}

Related

Put String[] in a String[][]?

Ok, soo what I'm trying to do, I have an oject with a attribut which looks like String[][], and I want to fill this one by calling a function and fill this String[][], one by one.
So here is what I tried but I get an error telling me :
"The type of the expression must be an array type but it resolved to String"
When I try to do
Produit[NbrProduit][0] = Produit[0];
My code :
public String[][] Produit = new String[MAX_Produit][2];
public void GetInfo1(String Client, String[] Produit,int NbrProduit){
Produit[NbrProduit][0] = Produit[0];
Produit[NbrProduit][1] = Produit[1];
Produit[NbrProduit][2] = Produit[2];
I don't understand why I get this because I'm filling a String field with an another String, right ? no ?
Sorry for my english.
Your parameter name (a 1D array) is the same as your instance variable name (a 2D array), so you're actually referring to your parameter only. Either use a different name (recommended), or use this.Produit when referring to your 2D array.
i.e.
public void GetInfo1(String Client, String[] produitParam,int NbrProduit){
Produit[NbrProduit][0] = produitParam[0];
Produit[NbrProduit][1] = produitParam[1];
Produit[NbrProduit][2] = produitParam[2];
Produit is a two dimensional String array, which means each of its element will be a string array. So you need to assign the element with the array of String and not just one String. Try this if it makes sense for your logic:
this.Produit[NbrProduit][0] = Produi;

Why is String[] args not initialized for it to be used like other String Arrays?

I'm learning Java and I was wondering, how String args[](main's argument) works. For other string arrays defined in a method, they need to be initialized with a fixed dimension for them to be used.
For example,For entering 10 or less elements in a string, I need to type String a = new String[10];
However, if I just type String a; and then type a[0] = "Word;", I get a "variable a might not have been initialized" error.
However, for String args[], I don't need to type String[] args = new args[]. Why is it so? Also, is it possible to create a string with infinite size like String args[]? (Sorry if I wasn't clear)
For other string arrays defined in a method, they need to be initialized with a fixed dimension for them to be used.
Well, that is what happens in case of String... argument of the main method. It gets initialized with the fixed number of arguments you pass as command line args. But after that, you can't add anything to the array, as the size is now fixed. If you don't pass any argument, it's length will be 0.
Note that the argument type is actually a varargs, and not a String[], although, internally the former is converted to the later anyways. The benefit you get with varargs is, you can pass variable number of arguments without explicitly creating an array.
Also, is it possible to create a string with infinite size like String args[]?
No the size of array is not unlimited. Since the type of args.length is an int. The maximum number of elements logically can be 2 ^ 32 - 1. But actually it's not even that. Memory would probably overflow much before than that.
Also note that, since we are talking about method formal parameter, there is still a restriction of maximum method size. As per JVM, the maximum size of method is restricted to 65536 bytes.
For Example:
public static void test(String... names) {
System.out.println("Names array length: " + names.length);
names[names.length] = "xyz"; // This would fail as expected.
names = new String[10]; // this however you can do. Re-assign a new array to names
}
public static void main(String... args) {
test("a", "b", "c"); // pass 3 arguments
test("a", "b"); // pass 2 arguments
}
It's only an information, that the parameter is of type String[], so it's a table of Strings.
It is a type, not any kind of initialization.
The JVM is setting up the String[] argument for you prior to passing control to your main(), sort of like this:
class InternalThingYouDoNotSee {
String[] args = build args[] from command line
Class.forName("YourClass").newInstance().getDeclaredMethod("main").invoke(args);
}
class YourClass {
public static void main(String[] args) {
/....
}
}

Is it possible to create a method with variable number of input values?

I want to create a method along the lines of [return] methodName(int numberOfTimes, String[numberOfTimes] strings), meaning that, depending on the value of numberOfChoices, I can add that number of String values to the method.
I've wondered and, as I wrote it, it wouldn't work because it would fail at compile time, because numberOfChoices isn't defined, and, if it would compile, it'd still be tricky to work it out.
I think my best bet is going with String... strings and do a for loop like this:
void methodName(int numberOfTimes, String... strings) {
for(int i = 0, i < numberOfTimes; i++) {
// do something with strings[i]
}
}
But I still wonder if what I originally wanted was possible.
EDIT: I'm dumb and am always thinking on "sharing" my methods outside of the workspace, that's why I want it to work on the most general way possible. Solution is actually removing numberOfChoices and just introducing as many String objects as needed in methodName. Something along the lines of methodname("One", "Two"). So, fixed code would be...
void methodName(String... choices) {
for(int i = 0; i < choices.length; i++) {
// do something with choices[i]
}
}
if the variable parameter is always of the same type (like strings) you could use an array or list as a parameter, the method won't care what the size of the array is, just that it's an array
void methodName(int numberOfTimes, String[] myStrings)
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of String arguments. You could then use loop without knowing the number like:
for (String stringParam: args) {
// your logic on stringParam
}
In java arrays are dynamic so their is no need to specify index within method argument
[return] methodname(int numberOfTimes, String[] strings)
it works
Java treats variable arguments as arrays, so you can iterate over strings like normal.
Example (returning all the strings concatenated with spaces):
public void wordsToSentence(String... words) {
final StringBuilder builder = new StringBuilder();
boolean notFirst = false;
for (String s : words) {
if (notFirst) builder.append(" ");
else notFirst = true;
builder.append(s);
}
return builder.toString();
}

Using class variables in methods

In java how to use class variables in methods?
this is the code that I have
public class ExamQ3a {
String[] descriptionArr = new String[50];
static int[] codeArr = new int[50];
public static void displayItems(int count, int[] codeArr,
String[] descriptionArr) {
count = this.codeArr.length;
for (int i = codeArr.length; i < codeArr.length; i--) {
}
}
}
The line that is being highlighted here is the count = this.codeArr.length; the error that I am getting is that the non-static variables cannot be referenced from a static context. But I already made the variable static. So what gives?
So as per request only! not that I want to ask the whole question, just to know why I want to use static, this is a practice question
You are to develop a simple application system to manage the inventory
in a company. The system should be able to maintain a list of up to 50
items. Each item has a unique integer code and a description.
(a) Write Java statements that declare and create two arrays to store the
code and the description of the items.
(b) Write Java method with the following method signature:
public static void displayItems(int count, int[] codeArr, String[] descriptionArr)
This method displays the code and description of all items in the company
in tabular form with appropriate column heading.
Parameters: codeArr: the array that stores the codes of the items
descriptionArr: the array that stores the descriptions of the items
count: the number of items in the system
There is no this in the static world. Get rid of it. To explain, this refers to the current instance, and when you're dealing with static methods or variables, you're dealing with items associated with the class, not with any one particular instance. So change the code to:
count = codeArr.length;
Edit 1
As an aside, you don't want to bunch up your closing braces like } } } which makes your code very difficult to read and follow. White space is free, so might as well use it judiciously to improve code readability.
Edit 2
You state:
so how would I reference the array codeArr to the class variable codeArr?
You're inside of the class, and there's no need to use the class variable name here since it is assumed to be used. Just use the static variable or method name and you should be golden.
Edit 3
Your use of static for this type of variable gives the code a bad smell. I'm thinking that your entire program would be much better off if this were an instance variable and not a static variable. For more discussion on this, you may tell us why you decided to make the variable static.
Is you're going to reference a static variable having the same name as a method parameter you prefix the static variable with the name of the class. In this case it would be ExamQ3a.codeArr.
The other way to handle this is to pick different names for your method parameters, or start using a common prefix for instance/static variables.
Another point to note is that, in the following piece of code statement1 will never be executed:
for (int i = codeArr.length; i < codeArr.length; i--) { statement1; }
it should be either
int length = codeArr.length;
for (int i = 0; i < length; i++) { ... }
or
int length = codeArr.length;
for (int i = (length-1); i > -1 ; i--) { ... }

Using an internal class to make a custom object, creating an array of that object, and access information in that object using Java

Code first questions later...
public class Program2
{
//The custom word object used when parsing the input file
class Word
{
public String wordname;
public int count;
public int uniqueWord = 0;
public Word(String word)
{
wordname = word;
count = 1;
}
public boolean wordExists(String word)
{
if (word == this.wordname)
{
this.count++;
return true;
}
else
{
return false;
}
}
public int getCount(Word word)
{
return this.count;
}
public String getName(Word word)
{
return this.wordname;
}
}
// The main method
public static void main(String[] args) throws IOException
{
//new array of words size 100
Word[] words = new Word[100];
//set the first word to bananna
Word words[0] = new Word("bananna");
//print bananna
System.out.print(getName(words[0]));
}
}
Ok, so with what I know about Java, the code above should let me make an array of words, set the first to "bananna", and print it out. I have little experience making a custom class like this, and I can't find a good resource to model. Also, I am not 100% sure I understand calling static/nonstatic methods, so I'm sure some of the errors are from that as well.
What the program should do eventually, as a reference for why I am doing this, I have to take information in from a file (delimited strings aka Words) and see if it already exists in the array of words (and increment that word's count if it does), if it doesn't then make a new word.
Errors I'm getting are here:
Program2.java:116: ']' expected
Word words[0] = new Word("bananna");
^
Program2.java:116: illegal start of expression
Word words[0] = new Word("bananna");
^
2 errors
Any other information that you need let me know. I'll be back to check this post in an hour. Thank you for any help you have!
Word words = new Word[100];
Your main problem I can see is that Word[100] is an Array type that holds Word objects. You'll need the words variable to be of type Word[], not just of type Word.
Regarding static and non-static, think of it this way: You've written a Word class, and then you can create as many Word objects as you like that belong to that class. When something is static, it means it belongs to the Word class, so it belongs to the definition of a word without belonging to any particular word. In contrast, something that is not static will belong to a particular Word object.
You have syntax errors when you try to create the array, you should have:
Word[] words = new Word[100];
If you want to invoke Word.newWord() without calling the method on an instance of the Word class, this method needs to be static.
The issue is with the way you are creating Array of Objects. You should declare the array of Class and then create objects:
//new array of words size 100
Word[] words = new Word[100];
//then Create objects
words[0] = new Word("apple");
Let's start with the first error message. This is telling you that Word[] and Word are incompatible types. The [] at the end tells you that this is an array of Word objects. In other words, Word words declares a reference to a single Word object. Whereas your use of new allocates an array of them. To fix this simply change to Word[] words.
I won't go into detail about the other error messages because they will likely change after you fix this one. Good luck with your Java!

Categories