can any one help me in this error in java? - java

i create hash table in java but there is aproblem in it when adding elements in it.
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<sum2 , g>;
the error in second line where define sum2 is variable contain integer value and g variable contain string value. i dont know where the problem in putting elements in hash table.i want to add the values of this variables in hash table each time as the values change.

To mutate an object, you have to call its properties. An object property is either a field or a method. In your case put is a method of the hashT object. A method call is done by writing the object name, then the dot operator, then the method name and finally the arguments surrounded by parenthesis:
objectName.methodName(argument1, argument2, ...);
The problem is here:
hashT.put<sum2 , g>;
put is a method and to call it you have to surround the arguments (sum2 and g) with parenthesis:
hashT.put(sum2, g);

You need to follow the comments and edit your title so its a meaningful title that will help other people understand what your question is about.
Also, when you get an error, copy the big red text that is displayed in the console (color depends on which editor you are using), also known as the error's "Stack Trace" and past it into your question somewhere. This will help us pinpoint what is going on, and the error title itself will likely give away to us exactly what's wrong.
However, without any context on what the error is and what is before or after those two lines of code it is difficult to determine if you have previously defined sum2 or g as a variable that stores values. I am going to assume you haven't assigned at least one of them, likely g as a variable.
For experimental purposes, try replacing those two lines of code with:
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<0 , "g">;
That is putting zero (0) as an explicit integer and g as an explicit string into the hashtable. If you need to put variables into there, then you need to define them before hand, like this:
int sum2 = 3 + 4;
String g = "Some String";
Hashtable <Integer,String> hashT=new Hashtable<Integer ,String >();
hashT.put<sum2 , g>;
Now the integer value 7 is stored as the hash and the string Some String as the mapped value.

Related

Java in Android Studio: Weirdness when writing value into array of user defined class

I am writing my first app in Android Studio, I am a self-taught novice. When I write data into the subscript of an array I have created as a user-defined class the value is written into an adjacent subscript as well! Have traced to some code where I move data down one position in the array, thought I could do this in one operation, but it seems this messes something up and I need to copy each member of the class individually.
Here is my class
class LeaderboardClass
{
public String DateTime;
public String UserName;
public long Milliseconds; //0 denotes not in use
}
Here is my array declaration
LeaderboardClass[] LeaderboardData = new LeaderboardClass[LeaderboardEntries];
I want to move some data from subscript j to subscript j+1
I tried
LeaderboardData[j + 1] = LeaderboardData[j];
I thought this would copy all the data from subscript j to j+1
Then when I subsequently write to the array I (subscript i) I get the correct entry I made, plus a duplicate entry in the adjacent subscript i+1.
When I rewrite the above to:
LeaderboardData[j + 1].UserName = LeaderboardData[j].UserName;
LeaderboardData[j + 1].DateTime = LeaderboardData[j].DateTime;
LeaderboardData[j + 1].Milliseconds = LeaderboardData[j].Milliseconds;
Everything else behaves as expected. So I was wondering exactly what is happening with my first (presumably incorrect) code?
Thanks.
In Java, there's a difference between primitive values and objects (instances of classes): Primitives are stored by value whereas objects are stored by reference. This means that your code would work as you expect if you were using integers. However, since you are using a class, the array merely stores the references to those objects. Hence, when you do LeaderboardData[j + 1] = LeaderboardData[j]; you are merely copying the reference of that object. Therefore, LeaderboardData[j + 1]and LeaderboardData[j] will point to the same object.
Sidenote: If you run your program with a debugger, you can actually see this in action:
The number behind the # denotes the reference number and if you look closely, you can see that the objects at indices 8 and 9 both have the reference #716.
To fix this, I would suggest that you use lists instead of arrays as they allow you to remove and add new entries. The standard list implementation is an ArrayList but in your use-case, a LinkedList might be more efficient.
Lastly, a closing notes on your code: For variable names (like DateTime, UserName or LeaderboardData should always start with a lowercase letter to distinguish them from classes. That way, you can avoid lots of confusion - especially because Java also has a built-in class called DateTime.

Saving a String into a file, then loading it into a String variable will give a "different" string that seems to have the exact same name [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
So I am having an issue, I put my self to the test of creating a 2D sandbox game kind of for fun, but has turned out evolving into something a bit more after about a week, but, to the point, I am saving chunk data into a few files, these are just .file or, just the most basic file type I assume, and the problem persists even using .txt files.
So what's happening is after saving a file containing the object name, x, and y positions, I am creating an object in a linked list using that information, when I enter a new "chunk", but things are not exactly right, somehow, my images load up for the tiles correctly, which is handled in the constructor for that tile, being called after it is added to the list, however, what made me notice is I have a check in the tiles update method, to see if it wants to change to a different grass texture, and it doesn't happen, so I did some checking and printing, and well, I can tell that the name variable certainly contains the desired name, eg. "dirt", however it does not equal "dirt", so I thought it was catching some spaces and I even trimmed the String, and when I run a test like
if(name == "dirt")System.out.print("dirt is actually "+name);
else System.out.print("dirt is apparently not "+name);
and the result is always, "dirt is apparently not dirt", with no spaces, and even when looking in the actual file I save it to, it saves the name fine, I have them saving in an order like so;
name x y
eg.
dirt 0 560
dirt 28 560
and so on, these all load in position perfectly fine and what stumps me is that the initial image loads in correctly, which is quite explicit, a switch statement to determine what the image, material type and such should be..
I was wondering if anyone has come across something like this and what it could possibly be.
Also any code desired I will add to the desc.
(I didn't know so many people would be so quick to help. Thank you all, I know it was a simple problem, but it had me super confused, now thanks to you all I understand something about comparing variables and objects I should have really known before, and which is really important
.)
Chances are the result is "dirt" but you're not testing it correctly.
Test should be if name.equals("dirt") ... not the equality operator ==.
See: How do I compare strings in Java?
Equality in Java:
String dirt1 = "dirt";
String dirt2 = new String("dirt");
System.out.println(dirt1 == "dirt"); // TRUE
System.out.println(dirt1 == dirt2); // FALSE
System.out.println(dirt1 == dirt2.intern()); // TRUE
System.out.println(dirt1.equals(dirt2)); // TRUE

Parsing a string into different variable types

Relatively new to programming here so I apologize if this is rather basic.
I am trying to convert string lines into actual variables of different types.
My input is a file in the following format:
double d1, d2 = 3.14, d3;
int a, b = 17, c, g;
global int gInt = 1;
final int fInt = 2;
String s1, s2 = "Still with me?", s3;
These lines are all strings at this point. I wish to extract the variables from the strings and receive the actual variables so I can use and manipulate them.
So far I've tried using regex but I'm stumbling here. Would love some direction as to how this is possible.
I thought of making a general type format for example:
public class IntType{
boolean finalFlag;
boolean globalFlag;
String variableName;
IntType(String variableName, boolean finalFlag, boolean globalFlag){
this.finalflag = finalFlag;
this.globalFlag = globalFlag;
this.variableName = variableName;
}
}
Creating a new wrapper for each of the variable types.
By using and manipulating I would like to then compare between the wrappers I've created and check for duplicate declarations etc'.
But I don't know if I'm on the right path.
Note: Disregard bad format (i.e. no ";" at the end and so on)
While others said that this is not possible, it actually is. However it goes somewhat deep into Java. Just search for java dynamic classloading. For example here:
Method to dynamically load java class files
It allows you do dynamically load a java file at runtime. However your current input does not look like a java file but it can easily be converted to one by wrapping it with a small wrapper class like:
public class CodeWrapper() {
// Insert code from file here
}
You can do this with easy file or text manipulations before loading the ressource as class.
After you have loaded the class you can access its variables via reflection, for example by
Field[] fields = myClassObject.getClass().getFields();
This allows you to access the visibility modifier, the type of the variable, the name, the content and more.
Of course this approach presumes that your code actually is valid java code.
If it is not and you are trying to confirm if it is, you can try to load it. If it fails, it was non-valid.
I have no experience with Java, but as far as my knowledge serves me, it is not possible to actually create variables using a file in any language. You'll want to create some sort of list object which can hold a variable amount of items of a certain type. Then you can read the values from a file, parse them to the type you want it to be, and then save it to the list of the corresponding type.
EDIT:
If I were you, I would change my file layout if possible. It would then look something like this:
1 2 3 4 //1 int, 2 floats, 3 booleans and 4 strings
53
3.14
2.8272
true
false
false
#etc.
In pseudo code, you would then read it as follows:
string[] input = file.Readline().split(' '); // Read the first line and split on the space character
int[] integers = new int[int.Parse(input[0])] // initialise an array with specefied elements
// Make an array for floats and booleans and strings the same way
while(not file.eof) // While you have not reached the end of the file
{
integers.insert(int.Parse(file.ReadLine())) // parse your values according to the size which was given on the first line of the file
}
If you can not change the file layout, then you'll have to do some smart string splitting to extract the values from the file and then create some sort of dynamic array which resizes as you add more values to it.
MORE EDITS:
Based on your comment:
You'll want to split on the '=' character first. From the first half of the split, you'll want to search for a type and from the second half, you can split again on the ',' to find all the values.

Fill arrays with data from block of string in java

I want to fill 4 arrays with specific data from block string
I got blocks like this
00:0035:0063:1705211023:00:
11::7027661000300976376:
99:59:07027661000300976376:::::
05:11:10000:::00 09:11:8510 07:::::1490:::
99:65:00:00:00:00:00:01000000000002140331410062269000000126300000000
99:64:00:00:00:00:00:00000355600200000000022700000000000000000001
99:01:227:1490:30:0:0:0:0:0:1:0:324
****Segundo Ticket PANGUI**** 99:00:35:63:1705211023:0:1:19353:63895896:1490:0:::::
99:150:0|1|H014|35|63|210517102100|
and I want to check if 00:.. , 05:11:.. , 99:65.. , 99:64... and 99:01...headers exists and stores data for specific field from each row, for example in line or row 99:65.. I will store the last field. If no exists one or more, I must be store zero, something like this
if exist 99:11 then Arr11 =specificfieldfrom9911, else arr11 = "0"
So that for each block have a structure or set of arrays that identifies the fields of each block
Arr00
Arr0511
Arr9965
Arr9964
Arr9901
how can I achieve this? any help would be great.
after you get the individual string you can use startsWith("") method on the strings. Eg. Assuming the string that came is on a variable called inputString you can use
if(inputString.startsWith("99:65")){
//do what you want to do
}
i hope this helps

Mapping Color Codes To Int in Java

I'm trying to write a change color method in Java that accepts an int parameter and changes that color based on that int. Valid colors will be in the range 1 - 6 for the six colors. You may decide which number (1-6) maps to which color. If the value is not in this range, make the circle red.
I am trying to do this without the use of an array list, but I am unsure how. Any ideas?
I've tried:
if(newColor == 1) {
newColor = "yellow";
}
And I get an error message saying 'incompatible types: java.lang.String cannot be converted to int.'
I've also tried:
if(newColor == 1) {
newColor.equals("yellow");
}
And I get an error message stating 'int cannot be dereferenced'.
1 is an int literal. If the compiler allows you to test newColor ==, then that means newColor must be an int variable. Being an int variable, it is only allowed to hold int values.
"yellow" is a String literal. The compiler will not allow you to assign a String value to an int variable. You may only assign String values to String variables.
You're going to need two variables: One to hold the given int value, and one to hold the String result.
Other languages (e.g., Ruby) might let you do it differently, but if you're going to use Java, then you are going to have to work within the Java rules to solve your problem.

Categories

Resources