This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed 7 years ago.
It may sound so silly to ask but still I want to know what will happen if i assign value of string within for loop. Let's say
String name = " darsha" ;
for ( i = 0 ; i < 10 ; i ++ )
{
name = darsha ;
}
What will happen internally? Will there be only one name instance in string pool or 10
This will unnecessary utilize memory as well cpu of your machine.
As output going to ramain the same that name="darsha"
So unneccesary wasting of memory,cpu utilization 7 wastage of java heap nothing else.
String name = " darsha" ;
for ( i = 0 ; i < 10 ; i ++ )
{
name = "darsha" ;
}
yes there will only be ONE name instance. :)
and there is a mistake in your internal name as well. It should be corrected with inverted commas as the darsha is a string value. name = " darsha" ;
You must add int before "i" in the loop,and it should be " darsha", instead of just darsha,if you modify like that the last result is name = " darsha"
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Good day, I am fairly new to Java and is wondering how do I give letters its corresponding int value like the image below. Currently stuck on this for a project I am doing. For example, when user inputs ABC, the output is 321, since it requires it to be reverse.
this image here
This would work :
public class Test {
public static void main(String args[]) throws Exception {
String str = "ABC";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c-64);
System.out.println(sb.reverse());
}
}
Loop Unicode code points
Get the Unicode code point number of each character in the string.
Get the count of code points by calling String#codePointCount.
Then loop each code point by calling String#codePointAt. Notice that we must use annoying zero-based counting rather than ordinal numbers, an all-too-common and unfortunate hold-over habit from the earliest days of programming.
String input = "Hi😀" ;
int countCodePoints = input.codePointCount( 0 , input.length() ) ;
for( int i = 0 ; i < countCodePoints ; i ++ )
{
System.out.println( "i: " + i + " | " + input.codePointAt( i ) ) ;
}
See this code run live at IdeOne.com.
i: 0 | 72
i: 1 | 105
i: 2 | 128512
Avoid char
Other Answers on this page unfortunately use the char type. That type is now legacy, dating back to original versions of Java.
That type is obsolete because it cannot address even half of the 143,859 characters defined in Unicode. For fun, run this code to see what happens when we use char type to look at the same input string seen above: "Hi😀".chars().forEach( c -> System.out.println( c ) ) .
Your solution
Back to your specific example of input text:
String input = "ABC" ;
int countCodePoints = input.codePointCount( 0 , input.length() ) ;
for( int i = 0 ; i < countCodePoints ; i ++ )
{
System.out.println( "i: " + i + " | " + input.codePointAt( i ) ) ;
}
When run:
i: 0 | 65
i: 1 | 66
i: 2 | 67
Since this is homework, I will leave to you the work of subtracting and reversing.
Additional reading: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).
Iterate over each character (in reverse) and attain the ASCII value (reference this question: https://stackoverflow.com/a/16458580). Then subtract its value based on ASCII (reference this table: https://www.ascii-code.com/). I would recommend sanitizing the input so that letters are either only uppercase or lowercase (depends on your requirements however).
The easiest/quickest way is using a switch statement. For example,
public static int charToInt(char c) {
switch(c) {
case 'A':
return 1;
case 'B':
return 2;
//...
}
}
You can make a similar function for the reverse with a method prototype similar to this:
public static char intToChar(int i)
To convert a String to an array of characters (char[]) use the method String.toCharArray. Once you have your char[] arr, use arr.length to get the size of the array. Use that size to create an integer array (int[]) with the same length, and you can loop through the character array and convert them to integers using your custom conversion method.
I would suggest Map<Character, Integer>. You can assign Integer values to Characters and you can always get it with the simple getValue() method from the Map interface.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
For example if:
String str = "100101010";
Then following should happen:
a[0]=1
a[1]=0
a[2]=0
...
It should hold for large strings also (up to 64 characters).
One hint: find a chart for ASCII. http://www.asciitable.com/index/asciifull.gif The code for "0" is 48 and the code for "1" is 49. You can convert characters to numbers just by subtracting 48 from the ASCII value.
int value = str.charAt(0) - 48;
It's important to realize that a Java char is just an integer type just like int and byte. You can do math with them. With that idea in mind, you should be able figure out the rest yourself.
(This is technically a duplicate since I answered a similar question long ago, but I can't find it, so you get a freebie.)
public static int[] getAsArray(String value){
// not null ; not empty ; contains only 0 and 1
if(value == null || value.trim().length()<1 || !value.matches("[0-1]+")){
return new int[0];
}
//if it necessary !value.matches("[0-1]+" regex to validate
value = value.trim();
value = value.length()>64 ? value.substring(0,63) : value;// up to 64 characters
int[] valueAsInt = new int[value.trim().length()];
for (int i = 0 ;i<value.length();i++){
valueAsInt[i]=(int)value.toCharArray()[i]-48;
}
return valueAsInt;
}
also if it's possible use shor or byte type as it's enoght to store 0,1 and you consume less memory as with int
I don't know why you want to do this, but it is a simple problem.
public static void main (String[] args) {
String s = "111232";
String element[] = s.split("");
System.out.println(element[0]);
System.out.println(element[1]);
System.out.println(element[2]);
System.out.println(element[3]);
System.out.println(element[4]);
System.out.println(element[5]);
}
These questions might have really simple answers but in this code
public void setupYears()
{
ArrayList<String> years_tmp = new ArrayList<String>();
for(int years = Calendar.getInstance().get(Calendar.YEAR)-90 ; years<=Calendar.getInstance().get(Calendar.YEAR);years++)
{
years_tmp.add("Year"+years+"");
}
Y = new JComboBox(years_tmp.toArray());
Y.setLocation(404,310);
Y.setSize(250,25);
Y.setEditable(false );
firstPanel.add(Y);
}
How do I firstly reverse the years so the first year would be the current year and the last year would be 90 years ago instead of vice versa?
Also how would I put the "Year" as the first object in the JComboBox instead of "Yearxxxx"?
"xxxx" being whatever year is displayed in the JComboBox
To solve the ordering problem:
for(int years = Calendar.getInstance().get(Calendar.YEAR) ; years>=Calendar.getInstance().get(Calendar.YEAR)-90;years--)
And to put "Year" in the first box, simply add the line
years_tmp.add("Year");
before your for loop.
Hope this helps.
In PL/I there's a nice statement called "PUT DATA" which is used like so:
NAME := 'ROBBY'
AGE = 30
PUT DATA ( NAME, AGE )
The output from that statement would be:
NAME = ROBBY, AGE = 30
To do so in Java would require a lot of care with quotes, spaces, and plus signs:
System.out.println ( "Name = " + name + ", age = " + age ) ;
I'm far too new at Java to have a feel for how impossible making a "putData" method would be. I should think about it first, I guess, but I mainly wondered if maybe it already exists, even in a one-argument-only form.
putData (name);
would very cleanly produce
name = ROBBY
vs.
System.out.println( "name = " + name )
which is nerve-wracking even with just one "equation" to display.
What you want is not possible in Java, since a method can not - and should not(!) - have any knowledge about the expressions used to calculate the values used for arguments. What if someone would write:
putData("ROBBY")
There is no variable name - what should putData print?
If Java had a map literal, you could have something like:
putData({name:"ROBBY"})
and putData would know that name is the key and "ROBBY" is the value and know how to print it. Still not what you wanted - but close.
Anyways, I also dislike string concatenation, and prefer to use printf:
System.out.printf("name = %s\n",name);
You still need to write name twice(can't go around that), but it's less ugly.
I'm answering my own first question of many months ago.
The PL/I "put data" statement can be faked by the Netbeans code template soutv:
System.out.println("${EXP instanceof="<any>" default="exp"} = " + ${EXP});
Typing soutv (and then hitting tab) gives the following template:
Since the first occurrence of args is "boxed" in "refactor format", it's semi-obvious that, whatever it is changed to, the other args changes similarly. So if I type now in the "args box" (and then hit enter), the statement becomes:
System.out.println("now = " + now);
It's good enough. Only thing I don't get is the PL/I nicety of being able to say
put data(a,b,c)
and getting
a = ..., b = ..., c = ....
But I'm sort of happy with the development. Hope it helps others.
System.out.printf("${EXP instanceof="<any>" default="exp"} = %s\n" , ${EXP});
The Netbeans template above does what Idan's suggestion (in Answer below)
System.out.printf("name = %s\n",name);
does and does NOT require typing name twice, besides having the advantage of enabling the following output:
x+y+z = 12
merely by typing x+y+z in the "args box", which results in this code:
System.out.printf("\nx+y+z = %s\n", x+y+z);
where the following initializations are given: x = 3 , y = 4, and z = 5.
I have question about assigning object to arraylist with nearly same objects, the objects come from another list which I want to add to the arraylist two times, and before I add it to another list, I need to set value a variable in those objects.
this the code,
ArrayList<ClassCourse> courses = new ArrayList<ClassCourse>();
ArrayList<ClassCourse> _courses = new ArrayList<ClassCourse>();
int index = 0;
for( int i = 0; i < courses.size(); i++ )
{
ClassCourse t = courses.get(i);
if(t.getSks()==4)
{
i--;
t.setSks(2);
t.setIndex(index); // I want to set this one
index++;
}
else
{
t.setIndex(index); // I want to set this one
index++;
}
_courses.add(t);
}
the problem is when I check the list by print it
for( ClassCourse t : _courses )
System.out.println( t.getIndex() + " " + t.getName() + " " +
t.getCourseCode() + " " + t.getSks() );
and this is what I get
1 Visi Komputer A 2
1 Visi Komputer A 2
2 Matematika Diskrit C 3
4 Jaringan Nirkabel dan Komputasi Bergerak A 2
4 Jaringan Nirkabel dan Komputasi Bergerak A 2
5 Pemograman Framework .NET A 3
6 Perancangan dan Analisis Algoritma E 3
8 Sistem Terdistribusi A 2
8 Sistem Terdistribusi A 2
9 Matematika Diskrit D 3
11 Manajemen Proyek Perangkat Lunak A 2
11 Manajemen Proyek Perangkat Lunak A 2
I can't get index's value increasing in right way
if(t.getSks()==4)
{
i--;
t.setSks(2);
t.setIndex(index); // I want to set this one
index++;
}
I guess you are decrementing i so that the object is added twice. But remember that its the same object that's getting added to the list. So when you set t.setIndex(index) it will change the value of index for the previous iteration.
This is because java deals with references only. So courses.get(0) and courses.get(1) returns a reference to the same object and hence this behaviour.
If you want the index to be different then you may need to clone the object and add it again to the list. You will need to think thru this and decide if you want another copy of the object or not.