How to add a char into an array using add? - java

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.

Related

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>", ""));
}

Changing the value inside an Array List?

for(int i = 0; i <= gameWord.length()-1; i++)
{
if(guessLetter.charAt(0) == (gameWord.charAt(i)))
{
hideword[i] = guessLetter.charAt(0);
}
else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
{
System.out.print("_" + " ");
}
}
I am making a hangman game and I have created an array list called hideword. Hideword prints an underscore for each letter that is in the word used for the game. I am trying to right a method that will swap the underscore with a letter the user guesses. However this code
hideword[i] = guessLetter.charAt(0);
Doesn't work. It gives me "array required, but java.util.ArrayList found
Anyone help?
Then, hideword must be an arraylist. Use hideword.set(index, character) for assignment instead of accessing it like an array.
An ArrayList is not an array, it's a List implementation (however, its implementation is backed by an array - hence the name).
Declare hideword as an array of char:
private char[] hideword;
and initialize it before use:
hideword = new char[gameword.length];
You code, without changing its basic intention, can be simplified greatly:
There's no need to subtract 1 from the length, just change the comparison operator
There's no need to have your if in the else - we already know it's not equal because we're in the else block
Rather than do useless print, assign an underscore to the array slot
Do one print at the end
Like this:
for (int i = 0; i < gameWord.length(); i++) {
if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
hideword[i] = guessLetter.charAt(0);
} else {
hideword[i] = '_';
}
}
// print hideword
You code would be simpler still if hideword didn't exist and you simply System.out.print() each character as you test it instead.

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(","));
}

Can any one Explain this behaviour in char array

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?

Splitting string algorithm in Java

I'm trying to make the following algorithm work. What I want to do is split the given string into substrings consisting of either a series of numbers or an operator.
So for this string = "22+2", I would get an array in which [0]="22" [1]="+" and [2]="2".
This is what I have so far, but I get an index out of bounds exception:
public static void main(String[] args) {
String string = "114+034556-2";
int k,a,j;
k=0;a=0;j=0;
String[] subStrings= new String[string.length()];
while(k<string.length()){
a=k;
while(((int)string.charAt(k))<=57&&((int)string.charAt(k))>=48){
k++;}
subStrings[j]=String.valueOf(string.subSequence(a,k-1)); //exception here
j++;
subStrings[j]=String.valueOf(string.charAt(k));
j++;
}}
I would rather be told what's wrong with my reasoning than be offered an alternative, but of course I will appreciate any kind of help.
I'm deliberately not answering this question directly, because it looks like you're trying to figure out a solution yourself. I'm also assuming that you're purposefully not using the split or the indexOf functions, which would make this pretty trivial.
A few things I've noticed:
If your input string is long, you'd probably be better off working with a char array and stringbuilder, so you can avoid memory problems arising from immutable strings
Have you tried catching the exception, or printing out what the value of k is that causes your index out of bounds problem?
Have you thought through what happens when your string terminates? For instance, have you run this through a debugger when the input string is "454" or something similarly trivial?
You could use a regular expression to split the numbers from the operators using lookahead and lookbehind assertions
String equation = "22+2";
String[] tmp = equation.split("(?=[+\\-/])|(?<=[+\\-/])");
System.out.println(Arrays.toString(tmp));
If you're interested in the general problem of parsing, then I'd recommend thinking about it on a character-by-character level, and moving through a finite state machine with each new character. (Often you'll need a terminator character that cannot occur in the input--such as the \0 in C strings--but we can get around that.).
In this case, you might have the following states:
initial state
just parsed a number.
just parsed an operator.
The characters determine the transitions from state to state:
You start in state 1.
Numbers transition into state 2.
Operators transition into state 3.
The current state can be tracked with something like an enum, changing the state after each character is consumed.
With that setup, then you just need to loop over the input string and switch on the current state.
// this is pseudocode -- does not compile.
List<String> parse(String inputString) {
State state = INIT_STATE;
String curr = "";
List<String> subStrs = new ArrayList<String>();
for(Char c : inputString) {
State next;
if (isAnumber(c)) {
next = JUST_NUM;
} else {
next = JUST_OP;
}
if (state == next) {
// no state change, just add to accumulator:
acc = acc + c;
} else {
// state change, so save and reset the accumulator:
subStrs.add(acc);
acc = "";
}
// update the state
state = next;
}
return subStrs;
}
With a structure like that, you can more easily add new features / constructs by adding new states and updating the behavior depending on the current state and incoming character. For example, you could add a check to throw errors if letters appear in the string (and include offset locations, if you wanted to track that).
If your critera is simply "Anything that is not a number", then you can use some simple regex stuff if you dont mind working with parallel arrays -
String[] operands = string.split("\\D");\\split around anything that is NOT a number
char[] operators = string.replaceAll("\\d", "").toCharArray();\\replace all numbers with "" and turn into char array.
String input="22+2-3*212/21+23";
String number="";
String op="";
List<String> numbers=new ArrayList<String>();
List<String> operators=new ArrayList<String>();
for(int i=0;i<input.length();i++){
char c=input.charAt(i);
if(i==input.length()-1){
number+=String.valueOf(c);
numbers.add(number);
}else if(Character.isDigit(c)){
number+=String.valueOf(c);
}else{
if(c=='+' || c=='-' || c=='*' ||c=='/'){
op=String.valueOf(c);
operators.add(op);
numbers.add(number);
op="";
number="";
}
}
}
for(String x:numbers){
System.out.println("number="+x+",");
}
for(String x:operators){
System.out.println("operators="+x+",");
}
this will be the output
number=22,number=2,number=3,number=212,number=21,number=23,operator=+,operator=-,operator=*,operator=/,operator=+,

Categories

Resources