Can any one Explain this behaviour in char array - java

Please find the code snippet.
public static void main(String args[]) {
char[] tmpArray = new char[10];
tmpArray[0] = 'a';
tmpArray[1] = 'b';
tmpArray[3] = 'd';
for (char element : tmpArray) {
System.out.print(element);
}
System.out.println(String.valueOf(tmpArray));
}
I was excepting the abd would display . but it is not displaying anything in forloop and it is displaying just "ab" in sop .
while i try to debug, array still holds the 4th element as 'd'. if if give d in 3rd element it is displaying properly. is it in contract per spec ?. It basically creates new String instance using Arrays.copy of the char. even the new char[] (value in String instance contain the 'd' as 4th element) . Is this behavior due to iterating in array while displaying...
there is no real use case. i just tried to solve other SO question ( irrelevant to this) and got this situation.
Thanks in advance.
Update:
Comments describing, they are seeing the 'd' at the end. that is what i excepted. but i didnt showed in my machine.
Ubuntu 12, Jdk 1.8 , eclipse kepler. is it releated to eclipse console then ?

You are assuming the array will default to a space (' ') character if you do not explicitly set it. Instead it defaults to null. See
Can we assume default array values in Java? for example, assume that an int array is set to all zeros?

Related

How to write a for loop for encoding and decoding in java? the program only encode one letter when I enter a string. College level 1 lesson [closed]

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 1 year ago.
Improve this question
I should write a encoding and decoding program in a class and then use it in main. The program needs the position for each letter to increase by 2.
When I run the program, the problem is that when I enter a string (like cookie), only the last letter is encoding. Here is a Screenshot of program running.
What is the problem for my program.
Thanks.
The lesson is very basic tho and the assignment are forbid students import any other java method like base64.Only use the starter code.
The code I will put here as well
public class SimpleCipher {
/*
* comments here to overview the method
*/
public String encode(String text) {
String result = "";
char[] chars = text.toCharArray();
int length = chars.length;
for (char x: chars) {
x+=2;
result = Character.toString(x);
}
// ToDo
// convert text into char array
// reverse the array using provided method (see below)
// loop over array adding 2 to each element
// convert the char array back to a String named result
// return the resulting String.
return result;
}
The main problem is that you are overwriting your result in each iteration.
Instead you want to append the character to the result string.
You can simply do that with
result = result + Character.toString(x);
result += Character.toString(x); // shorter version
result += x; // java can append characters to strings without explicit conversion
According to the comment that is - even tho it is working - not the desired solution anyways. The task is to create a new character array and fill it.
Do that by creating a new array of the same length as the original, iterating over the indexes of your arrays ( for (int i=0; i<chars.length; i++) ) and for each index write the updated character into the new array. The string class has a constructor that accepts a char array.

How can I fix my code to find a certain character in an array and make changes to that array

while (scan_file.hasNext()) {
String b = scan_file.nextLine();
// checks if string b contains the tag <h>
if (b.contains("<h>")) {
char arrayString[] = b.toCharArray();
for (int i = 0; i < arrayString.length; i++) {
if (arrayString[i] == '<') {
arrayString[i] = arrayString[i + 2];
}
System.out.print(arrayString[i]);
}
}
}
What I was expecting the program to do was(for now) iterate through the while loop and store each line as string 'b'.
I want to check if that string b contains a certain string like <h> for this example. And I want to convert string b into an array if it contains said string like <h> and iterate through that array to check for '<' and move the array up 2 spaces.
For example, string b had <h>hello, I wanted to eventually print hello because the program would have moved up 2 elements.
I feel like I got the loops and general idea on how I want to tackle the problem.. but when I ran the program, nothing printed so I don't know if I did the loops and if statements correctly.
I really don't know how to word my problem well, so bear with me and I'm sorry in advance.
All feedbacks are greatly appreciated (:
System.out.print(arrayString[i]); just print the ith character of arrayString, it's definitely not what you want.
In fact you don't have to convert a String to char[], String has many utils method can help you with your goal.
I won't give you full code , but I can give you some tips.
You can use String.indexof('<') to find the index of '<'.
You can use String.subString(startIndex) to get the subString start with the specified index.
Suppose your code scan_file.hasNext() and scan_file.nextLine() is work well. You can try code below to remove all from current line:
if (b != null && b.contains("<h>")) {
System.out.println(b.replaceAll("<h>", ""));
}

How to add a char into an array using add?

I am trying to coding Java and adding a char to an array. My idea is compare two char, if they are different, I will add them to an array and here is my code.
ArrayList<String> different = new ArrayList<>();
if (character.charAt(i) == (character.charAt(i+1)))
{
}
else
{
different.add(character.charAt(i+1));
}
But when I run my code, they said to me that "no suitable method found for add (char)" at line 6, and I can not run the code. Could you please give me some ideas? Thank you very much for your help.
The problem is that you are adding char datatype to an arraylist which is of type String. You need to change the code to:
ArrayList<Character> different = new ArrayList<>();
if (character.charAt(i) != (character.charAt(i + 1))) {
different.add(character.charAt(i + 1));
}
String::charAt returns a char, not a String. So your char cannot be put into a list holding String objects. Square peg, round hole.
Also char is a legacy type, limited to a subset of less than half of the over 110,000 characters defined in Unicode, restricted to code points in the “basic plane”. You should learn to work with code points as numbers to be able to handle any Unicode characters.
When you declared List<String> or ArrayList<String>, it means the List should contain type String or literals(something between double quote "". FYI, this is called Generic Type.
Use String#valueOf(char c) to create new String from a char. Example:-
//returns a type char
char c = character.charAt(i+1);
//use String#valueOf(char c) to create new `String` from variable `c`
different.add(String.valueOf(c));
** Oracle has good tutorial on Generic Type, you could refer to it.
https://docs.oracle.com/javase/tutorial/java/generics/index.html
ArrayList<Character> different = new ArrayList<>();
if (character.charAt(i) == (character.charAt(i+1)))
{
}
else
{
different.add(character.charAt(i+1));
}
///////////////////
Just add Wrapper class Character instead of String.

How to check if there are double letters in a 4 digit code in Java

The above question might seems vague but it's actually a very simple idea which i can't seem to figure out.
It basically is a 4 digit letter code containing letters from A to F for example: ABDF, BAAF, DBAF etc.
Now I'm trying to do some post input-handling where it must become impossible to enter a letter that is already in the code cause it has to be a unique 4 digit code with no repeating letter. I've been trying to make it work but none of my code seems to work so i'm back to scratch asking you guys for help :)
I hope this is somewhat clear otherwise i'll be happy to clear it up.
Thanks in advance.
Kind of a pseudocode but it would work.
String uniquePass="";
while(uniquePass.length<4){
String userInput=getUserInputChar()
if(uniquePass.contains(userInput))
rejectInputAndNotifyUser
else
uniquePass=uniquePass+userInput
}
public static boolean hasDuplicateChars(String string) {
Set<Character> chars = new HashSet<Character>();
for (char c : string.toCharArray()) {
if (!chars.add(c)) return false;
}
return true;
}
Set is a collection that contains no duplicate elements. We will use add method which returns true if this set did not already contain the specified element.
hasDuplicateChars functions iterates over characters in the input string using toCharArray function and for loop; each character is added to the chars set which is initially empty. If add method returns false it means that we have already encountered same character before. So we return false from our function.
Otherwise input is valid and method returns true.
using this function you'll be able to see if the string contains unique characters
public static boolean checkForUnique(String str){
boolean containsUnique = false;
for(char c : str.toCharArray()){
if(str.indexOf(c) == str.lastIndexOf(c)){
containsUnique = true;
} else {
containsUnique = false;
}
}
return containsUnique;
}
Update:
This will be ran everytime a user enters a character and if it fails, this would mean there is a duplicate. You have the choice of discarding that input or showing an error.
If you're validating the complete input, you can lean on the set semantics, and a few tricks
String s = "ABAF";
int count = new HashSet<>(Arrays.asList(s.split(""))).size();
if (count - 1 == 4) {
System.out.println("All ok");
} else {
System.out.println("Repeated letters");
}
the split("") will split the string to a an array like {"","A", "B", "A", "F"}.
The new HashSet<>(Arrays.asList(s.split(""))) will create a Set with String elements, and as the Set will bounce back the elements already contained, the size of the set for e.g. "AAAF" will be 3 (it'll contain the "", "A" and "F"). This way you can use the size of the set to figure out if all letters of a String are unique
If its while typing you'll than the solution depends on the input method, but you can have something like (pseudo stuff)
if (pass.contains(letter)) {
breakAndNotifyUser();
} else {
pass+=letter;
}

Workaround for declaring array in an if condition

I have a problem with this part of the code where I want to be able to declare an array and the size of which should be the corresponding no of splits in the string.
Or do I need to count the no of commas in the string and allocate size accordingly or is there a better solution.
String MapPath2[];
if(type.equals("comparative"))
MapPath2[]=args[1].split(",");
I haven't had a chance to code in java in the recent past. Please spare me if it is a silly question and guide me as a noob. Appreciate your help.
You don't need to declare the size, what you have is fine if you remove the extra []:
String MapPath2[];
if(type.equals("comparative"))
MapPath2=args[1].split(",");
The array split gives back to you has the appropriate size. If you need to know the resulting size, use MapPath2.length (after assigning it).
You'd probably want to do something in the else as well, so that MapPath2 has a definite value either way:
String MapPath2[];
if(type.equals("comparative"))
MapPath2=args[1].split(",");
else
MapPath2=null;
or more concisely:
String MapPath2[];
MapPath2 = type.equals("comparative") ? args[1].split(",") : null;
(Instead of the nulls there, if having an empty array is preferred for subsequent logic as is sometimes handy, replace null with new String[0] above and below. Other times, it's more handy to have the null as a "no data" flag.)
Side note: There are some overwhelmingly common code style conventions in the Java world that you would be best advised to use in your code:
Variable names should start with a lower case letter, so as not to be confused with class names.
The [] should go with the type name rather than the variable name.
Always use {} even when the body of an if or else is only one line.
Put spaces around operators and keywords for ease of reading.
Applying those:
String[] mapPath2;
if (type.equals("comparative")) {
mapPath2 = args[1].split(",");
}
else {
mapPath2 = null;
}
Many people also put the else on the same line as the }, so:
String[] mapPath2;
if (type.equals("comparative")) {
mapPath2 = args[1].split(",");
} else {
mapPath2 = null;
}
Or again, more concisely:
String[] mapPath2;
mapPath2 = type.equals("comparative") ? args[1].split(",") : null;
You can use List instead of Array if you don't know what size it needs be.
Then you can use
List<String> list = new ArrayList<>();
if(type.equals("comparative")){
Collections.addAll(list, args[1].split(","));
}

Categories

Resources