Suppose I have a String "CAA". What I am doing now is randomly adding some Character to it for e.g. lets say I am adding Character 'B' and 'D' and shuffle that whole Character ArrayList and placing them in some Buttons as below
Here my character ArrayList contains {'A','C','B','A','D'}
What I am trying to do is when I click on a button I want something like below
I mean only keep the Buttons that contain letters of Original string and disable all other Buttons.
Create a Custom Class that wraps a Character and a boolean flag to maintain that its original character.
class MyCharacter {
private Character c;
private boolean isOriginal;
public MyCharacter(Character c, boolean isOriginal) {
this.c = c;
this.isOriginal = isOriginal;
}
public Character getChar() {
return c;
}
public boolean isOriginal() {
return isOriginal;
}
}
Instead of adding Character into list. Add MyChracter object.
For original chracters pass boolean true in constructor and for later random ones pass false in it.
Do shuffling or whatever you want. At any moment iterate over the list. Get the MyChracter object and check whether its original or not.
This should be simple to do.
Hope this helps
Cheers
You could keep several different ArrayLists. One holds the characters that you display, one holds the original, and then when a button is clicked test to see if a button is in the original ArrayList before graying it out.
Related
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>", ""));
}
So I have probably an easy question, but I couldn't find anyone asking this question on Google, so now I'm here.
The problem is simple - I must copy a line of text that has white spaces and tabulators in it, but once I copy it inside my text (input) field, it removes all the tabulators for some reason, so it leave the text all in one big mess that I cannot filter anything out of it.
Any ideas what could be done so those input fields would allow tabulators?
P.S. By pressing tab while I'm inside the input field, it moves between the buttons, instead of inputting a tabulator.
The content of a TextField is represented by a private static class TextFieldContent. TextFieldContent implements insert(int index, String text, boolean notifyListeners) method to filter the input text. The method uses a static method from TextInputControl class to remove "illegal" characters, here is the implementation:
#Override
public void insert(int index, String text, boolean notifyListeners) {
text = TextInputControl.filterInput(text, true, true);
if (!text.isEmpty()) {
characters.insert(index, text);
if (notifyListeners) {
ExpressionHelper.fireValueChangedEvent(helper);
}
}
}
The last parameter in TextInputControl.filterInput(text, true, true) defines whether tab characters are "illegal" or not. It's set to true and as I mentioned before, that class is a private static final class and you can't extend it and override insert method.
The solution is to extend TextInputControl and create a custom Content class that doesn't remove tab characters.
As an alternative, you can use TextArea, text areas accept tab characters.
There are two classes. One is mine where i handle the events and other is main. There are 4 text fields and 3 buttons, one to add a name and a number, second to search a number by name and 3rd to clear the array list.
I'm trying to search the numbers by name, the problem is that when I add the name with number it will be added, but when I search it then it shows nothing in the text field.
This is my code where i handle three buttons, mine is the class where I handle events:
public void actionPerformed(ActionEvent event) {
ArrayList<mine> datalst = new ArrayList<mine>();
if (event.getSource() == b1) {
String getn=tf1.getText();
String getf=tf2.getText();
mine ob1= new mine(getn,getf);
datalst.add(ob1);
}
if (event.getSource()== b2) {
String name=tf3.getText();
// tf4.setText(name);
System.out.println("calling searching");
for (int i=0;i<datalst.size();i++) {
// System.out.println("calling searching");
mine s =(mine)datalst.get(i);
if (name.equals(s.getn))
tf4.setText(s.getf);
else
tf4.setText("nai mila");
}
}
if (event.getSource()==b3) {
datalst.clear();
System.out.println("clear all");
}
}
The problem is this line: ArrayList<mine> datalst = new ArrayList<mine>();. You are essentially creating a new array list each time, thus, when you go to search, the array list will be empty. Moving the decleration outside the method, thus making the datalst an instance variable should fix the problem.
As a side note, please also consider looking into naming conventions. In Java, class names use Pascal Casing, meaning that they start with capital letters, with each word starting with a capital letter: mine becomes Mine.
Also, please give good names. tf4, s, getf are not good names.
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;
}
I have created this function to check abecedarian with while loop (A word is said to be "abecedarian" if the letters in the word appear in alphabetical order, such as "abdest")-
public static boolean isAbecedarian(String s) {
int index = 0;
char c = 'a';
while (index < s.length()) {
if (c > s.charAt(index)) {
return false;
}
c = s.charAt(index);
index = index + 1;
}
return true;
}
I want to change this function to a recursive function and I have written this function -
public static boolean isAbecedarianrec(String s){
char first = s.charAt(0);
char second = first ++;
if (first<second){
return isAbecedarianrec(s);
}
return false;
}
recursive function is not working as it should and I am not getting the expected result. Please check and help me to pin point the issue with this function.
Note - As I mentioned this is not a homework question and it is part of my self Java learning.
Two issues:
The following code char second = first++ should be char second = s.charAt(1);
The recursive call should be return isAbecedarianrec(s.substring(1));
Finally, you need length checks where appropriate. On method entry, ensure the string has at least 2 characters if not, return true.
When using recursion, you need to keep two things in mind. First, the input to the recursive should in some way be different than the previous input. Second, there must be a valid stopping point so that you don't recurse infinitely and thereby run out of memory.
Typically with recursion you need two things:
A base case (e.g. empty string, zero, etc.)
A way to check part of the more complex case, and then reduce it to a simpler recursive call.
The empty string does form a good base case here - it's trivially abecedarian. So the first part of your recursive method should be to check for the empty string and return true. This forms the base case that will be the termination of your recursive method in the "happy path" case.
Otherwise, you know you have a non-empty string. The recursive decomposition can be achieved by checking its first character, then recursively calling with the rest of the string. However, in order to perform the check, you'll need to remember what the previous character of the string was (just like c in the iterative method), so you'll need an additional argument to the recursive call to act as a sort of variable.
This is not uncommon with recursion - often the majority of the work is done in a "helper" method, and the public method just calls this with initial/dummy values.
Putting these together then, a solution would look something like the following:
// s must not be null
public boolean isAbecedarianrec(String s) {
return isAbecedarianRecImpl(s, (char)0);
}
private boolean isAbecedarianRecImpl(String s, char c) {
if (s.isEmpty())
return true;
else {
if (c > s.charAt(0))
return false;
else
return isAbecedarianRecImpl(s.substring(1), s.charAt(0));
}
}
Java does not have pointer arithmetics (it seems you are trying to do something like that). You code will take the first char (always the first char of the String), and afterwards it will increment the char (turning 'a' into 'b' etc) and furthermore store the value to second also. This means that first and second will always contain the same value.
A simple (but not very efficient solution could be:
public static boolean isAbecedarianrec(String s, char c){
if (s.equals("")) return true;
char first = s.charAt(0);
if (first>=c){
return isAbecedarianrec(s.subString(1), first);
}
return false;
}
(Notice that I have also flipped the equality. That seemed to be wrong).
Call the function with the value of the lowest character. E.g.: isAbecedarianrec(s, 'a').
Notice that this solution (like yours) requires that the code points of the letters have the same numerical order as the alphabetical order of the letters. That is not generally correct, for example you will see strange results if the string contains both capital and small letters.
To create a recursive function, you need two things: an end case that stops execution, and some way to modify the successive calls to the recursive function.
In your case, you have one end case covered (the case where the string is not abecedarian), but not the other. For your function to ever return true, it needs to contain a return true statement or a return statement with a boolean comparison in it. The condition in this case would probably be finding the end of the string (being called with an empty string).
You are also missing a modification of successive calls: every call to isAbecedarian is made with the same string. Depending on what works best in Java, you could either shorten the string by 1 character on every call, or pass the index as an argument to the function and increment it on each call.