I have these two methods- My code doesn't seem to be working as planned
What is is supposed to do is- Go through the array of characters- If there's not another character the same in the array, it is supposed to add itself to the index variable-
This is my comparing method
private boolean isValid(char c) {
for(int i = 0; i < letters.length; i++) {
if(Arrays.asList(letters).equals(c)) {
return false; //Not valid
}
}
return true;
Full code is below though
public void generate(String first, String second) {
tempString = new StringBuilder(first+second).reverse();
letters = new char[tempString.length()];
for(int i = 0; i < tempString.length(); i++) {
letters[i]= tempString.charAt(i);
if(isValid(tempString.charAt(i))) {
index += i;
}
}
}
private boolean isValid(char c) {
for(int i = 0; i < letters.length; i++) {
if(Arrays.asList(letters).equals(c)) {
return false; //Not valid
}
}
return true;
}
There is no need to convert to a List (and a List is not a primitive char), you can use == for comparing primitive values (such as your chars). Something like,
private boolean isValid(char c) {
for (int i = 0; i < letters.length; i++) {
if (letters[i] == c) {
return false;
}
}
return true;
}
or with an enhanced for-each loop like
private boolean isValid(char c) {
for (char letter : letters) { // <-- for each letter in letters.
if (letter == c) { // <-- if the letter is equal to the argument.
return false;
}
}
return true;
}
You should also test for validity before adding to the array like
if (isValid(tempString.charAt(i))) {
letters[index] = tempString.charAt(i);
index++;
}
Arrays.asList(letters).equals(c) is comparing the list to the character (Is the list equal to this character which is not what you want.
To find if a character is in the string you can instead do
string.indexOf('a') which will return -1 if the character is not present and >= 0 if it is in the string.
Related
I have to write a boolean function that takes a string and check if a string is a palindrome or not in java.
Here is my code
static boolean isPalindrome(String input)
{
int i = 0;
last = input.length() - 1;
while (i < last) {
if (input.charAt(i) != input.charAt(last))
return false;
i++;
last--;
}
return true;
}
I want to add this part to my code but I got stuck on that if there is only one character mismatch I should consider it as valid palindrome.
Sample results:
“book” -> true
“refer” -> true
“” -> true
Instead of immediately returning false when two characters are different, you keep a count of how many pairs of characters are different:
static boolean isPalindrome(String input)
{
int i = 0;
int last = input.length() - 1;
int differentCount = 0;
while (i < last) {
if (input.charAt(i) != input.charAt(last)) {
differentCount++;
// only return false if more than one character is different
if (differentCount > 1) {
return false;
}
}
i++;
last--;
}
return true;
}
Add a boolean flag that tracks whether you already found a mismatching pair of characters:
static boolean isPalindrome(String input)
{
boolean firstMismatch = true;
int i = 0;
last = input.length() - 1;
while (i < last) {
if (input.charAt(i) != input.charAt(last)) {
if (firstMismatch) {
firstMismatch = false;
} else {
return false;
}
}
i++;
last--;
}
return true;
}
I have to create a public method called cancelPolicy(int polNum) which removes the policy from the client's list with the given policy number, if found. It should return true if the policy was found, otherwise it should return false. When a policy is removed from the array, the empty location in the array should be replaced by the last policy in the array.
The code I have written so far:
public int cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
}
}
return polNum;
}
What I don't understand is how to remove and replace from the array of policies[i].
This is precisely what you are looking for:
public boolean cancelPolicy(int polNum)
{
int n = policies.length-1; //optimization by making n = length-1
for (int i = 0; i <= n; i++) { //notice equals in condition
if (policies[i].getPolicyNumber() == polNum) {
policies[i] = policies[n]; //replace i with last if that's what you meant
policies[n] = null; //remove loitering
return true;
}
}
return false;
}
To replace the found policy, you need to do as follow:
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
policies[i] = policies[arrSize - 1];
policies[arrSize - 1] = null;
arrSize--;
return true;
}
}
return false;
}
And in you class you need to keep the number of policies:
private int arrSize;
Alternatively you can recreate the array:
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
int[] newArr = new int[policies.length - 1];
System.arraycopy(policies, 0, newArr , 0, i);
System.arraycopy(policies, i + 1, newArr, i, policies.length - i - 1);
policies = newArr;
return true;
}
}
return false;
}
And the best, but not sure if this option is available to you, would be to use a List or a Map
you cold get the last non null and then set the last element to null as well. this would "replace" it so you don't get duplicated policies. teachers like it when you think about stuff like that typically
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
for (int j = policies.length - 1; j >=0; j--){
if (policies[j] != null) {
policies[i] = policies[j];
policies[j] = null;
return true;
}
}
}
}
return false;
}
This is my input verifier:
public class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText().trim()
if (text.isEmpty() || text.length() == 0) return false;
// How verifier that if text contains digit, return false?
return true;
}
I need to recognize when text contains digit(s), it return false to me.
Is there any method Or i should use old way?(for loop)
This is one way of checking if text contains a digit:
boolean containsADigit = text.matches(".*\\d.*");
If you want to check if all characters are digits you can still use regular expressions, or try parsing the string as an integer:
boolean isDigitsOnly = text.matches("\\d*");
Using only very basic stuff:
public boolean containsDigit(String str) {
int n = str.size();
for(int i=1, i<n, ++i) {
if(str.charAt(i).isDigit()) {return true;}
}
return false;
}
Are you looking for a more faster way?
private boolean hasOnlyDigits(String str) {
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
How can I write the below code without using regex?
public static boolean validateCode(String code){
boolean hasAtLeastOneNumber = Pattern.compile("[0-9].*[0-9]")
.matcher(code).find();
boolean hasAtLeastTwoLetters = Pattern.compile("[a-zA-Z].*[a-zA-Z]")
.matcher(code).find();
boolean hasAtLeastOneHyphen = Pattern.compile("-")
.matcher(code).find();
}
How about
public static boolean validateCode2(String code) {
int numbers = 0, letters = 0, hyphens = 0;
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) numbers++;
if (Character.isAlphabetic(c)) letters++;
if (c=='-') hyphens++;
}
return numbers>=2 && letters>=2 && hyphens>=1;
}
For hasAtLeastOneNumber:
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
return false;
For hasAtLeastTwoLetters:
int numFound = 0;
for (char c : code.toCharArray()) {
if (Character.isLetter(c)) {
numFound++;
if (numFound >= 2) {
return true;
}
}
}
return false;
For hasAtLeastOneHyphen:
for (char c : code.toCharArray()) {
if (c == '-') {
return true;
}
}
return false;
If you don't want to use toCharArray, you could use:
for (int i=0; i<code.length(); i++) {
char c = code.charAt(i);
// do the rest of the test here
}
That's basically equivalent to using toCharArray except that it's slightly more confusing: someone who looks at the code would need to take a second or two to figure it out. With toCharArray it's obvious what you're doing.
You can loop through the string and test it for ranges of characters. See an example on IDEONE, or ask me if you need an explanation.
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(validarCodigo("No-numbers"));
System.out.println(validarCodigo("1-A"));
System.out.println(validarCodigo("This 1 Matches -- :-)"));
}
public static boolean validarCodigo(String codigo) {
int i;
char[] chars = codigo.toCharArray();
char current;
boolean tieneAlmenosUnNumero = false;
boolean tieneAlmenosDosLetras = false;
boolean tieneAlmenosUnGuion = false;
// Check for at least one number
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current >= '0' && current <= '9') {
tieneAlmenosUnNumero = true;
break;
}
}
// Check for at least two letters
int found = 0;
for (i=0; i<chars.length; i++) {
current = chars[i];
boolean lower = current >= 'a' && current <= 'z';
boolean upper = current >= 'A' && current <= 'Z';
if (lower || upper) found++;
if (found == 2){
tieneAlmenosDosLetras = true;
break;
}
}
// Check for at least one hyphen
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current == '-') {
tieneAlmenosUnGuion = true;
break;
}
}
return tieneAlmenosUnNumero && tieneAlmenosDosLetras && tieneAlmenosUnGuion;
}
}
I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}