check two conditions in if statement [closed] - java

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
I am checking for 2 conditions, and I need that both of them would work,
but work only one of them. Where I am making the mistake? I need to print indexes of positions of ch1 and ch2 in String text
import java.util.Scanner;
public class TestIndexOf {
private static String text;
private static char ch1, ch2;
public static void main(String[] args) {
TestIndexOf test = new TestIndexOf();
test.getInput();
System.out.println(test.getIndex(text, ch1, ch2));
}
public static void getInput() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter word and chars: ");
text = scan.nextLine();
ch1 = scan.next().charAt(0);
ch2 = scan.next().charAt(0);
}
public static int getIndex(String text, char ch1, char ch2) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch1) {
return i;
}
if (text.charAt(i) == ch2) {
return i;
}
}
return -1;
}
}

If I understand correctly, you want to know the position of both char1 and char2.
The way you have written your logic, it can only return one value.
You need to remove the return statement and collect the results in some variable.
Then return that variable instead at the end.
or something like this should work:
public class TestIndexOf {
// private static String text;
// private static char ch1, ch2;
public static void printIndex(String text, char ch1, char ch2) {
int count = 0;
boolean isCharAIndexNotPrinted = true;
boolean isCharBIndexNotPrinted = true;
for (int i = 0; i < text.length(); i++) {
if(count==2)
break;
if (text.charAt(i) == ch1 && isCharAIndexNotPrinted) {
count++;
isCharAIndexNotPrinted = false;
System.out.println("char1 is " + i);
}
if (text.charAt(i) == ch2 && isCharBIndexNotPrinted) {
count++;
isCharBIndexNotPrinted = false;
System.out.println("char2 is " + i);
}
}
}
}

Related

How do you double each letter in a string using a for loop and an if statement in java

I need to double each letter in a string using a for loop and an if-then statement. How can you comb through a string and test if each character is a letter or a symbol like an exclamation point? And then print the string back out with each letter doubled and each exclamation point tripled.
This is what I have so far. It's unfinished and it doesn't work at all, but am I on the right track?
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
boolean isLetter = false;
for (int i = 0; i < sentence.length(); i++){
isLetter = Character.isLetter(sentence.charAt(i));
if (i == sentence.length() || sentence.charAt(i) == ' ' || isLetter == false){
System.out.print(sentence.charAt(i) + sentence.charAt(i));
}
}
It looks like you were on the right way, then passed the right exit and carried on the wrong way.
for (int i = 0; i < sentence.length(); i++){ [...] } is a right way to iterate over a string's characters.
Character.isLetter(c) is a right way to check whether a character is a letter.
However, your condition is chaotic :
why would you make special conditions for spaces and end characters?
why is your isLetter condition negated?
I think your condition should simply be
if (isLetter) { /* print twice */ }
else if (isExclamationPoint) { /* print "thrice" */ }
else { /* print once */ }
Try this:
import java.util.*;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
StringBuilder sb = new StringBuilder();
for (Character c: sentence.toCharArray()){
sb.append(c);
if(Character.isLetter(c)){
sb.append(c);
}
else if(c == '!'){
sb.append(c).append(c);
}
}
sentence = sb.toString();
System.out.println(sentence);
}
}
When manipulating strings like this, it is best to use StringBuilder, which allocates a contiguous character buffer of a given size. You can count how big your output String needs to be, and pass this size to the StringBuffer on construction.
I would also recommend continuing to call String.charAt for maximum efficiency.
You may also want to encapsulate your routine in a function. You can take the input as a CharSequence for maximum utility.
public class DoubleLetters {
private static int getRepetitionCount(char c) {
if (Character.isLetter(c)) {
return 2;
} else if (c == '!') {
return 3;
} else {
return 1;
}
}
public static String doubleLetters(CharSequence in) {
int inLength = in.length();
int outLength = 0;
for (int i = 0; i < inLength; ++i) {
outLength += getRepetitionCount(in.charAt(i));
}
StringBuilder out = new StringBuilder(outLength);
for (int i = 0; i < inLength; ++i) {
char c = in.charAt(i);
int reps = getRepetitionCount(c);
for (int r = 0; r < reps; ++r) {
out.append(c);
}
}
return out.toString();
}
public static void main(String[] args) {
String test = "hello! world!";
System.out.print(doubleLetters(test));
}
}
In this specific case, you could alternatively allocate a buffer of size 3 * inLength, which will be large enough to hold any potential output string.

What am I doing wrong with my Java code for input validation? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So this program is supposed to be a game where a user enters a phrase and another user tries to guess the phrase. I'm having a problem with buying a vowel, however. No matter what I enter at line 41 (, it just goes past the loop. I made the validAnswer(String answer) method in the hopes that it would be useful in the loop but it doesn't look to be much help. I know there is a small thing I'm missing but I'm too new to Java to recognize it yet. What am I doing wrong?
I apologize for the long amount of code.
import java.util.Scanner;
public class PhraseGame {
public static void main(String[] args) {
// Initialize scanner
Scanner stdIn = new Scanner(System.in);
// Initialize variables
String sPhrase;
String answer = "f";
char cGuess = 0;
char vGuess = 0;
int count = 0;
int vowels = 0;
int consonants = 0;
int spaces = 0;
boolean gameOver = false;
boolean correct = true;
// Start the "fun" game
System.out.print("Please enter the phrase to guess at: ");
sPhrase = stdIn.nextLine();
// Create the temporary Array
char [] tmpArr = new char[sPhrase.length()];
for (int i = 0; i < sPhrase.length(); i++) {
tmpArr[i] = sPhrase.charAt(i);
}
// Gets the number of spaces
spaces = initTemplateArray(sPhrase, tmpArr, spaces);
printTemplateArray(tmpArr);
while (!(endGame(gameOver, spaces, consonants, vowels, sPhrase))) {
cGuess = getConsonant(stdIn, cGuess);
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.next();
if (answer == "y") {
getVowel(stdIn, vGuess); }
else if (answer == "n"){
break;
}
} while (!validAnswer(answer));
// Updates the array and prints it
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, count, vowels, consonants);
printTemplateArray(tmpArr);
// Checks if the game is over
endGame(gameOver, spaces, consonants, vowels, sPhrase);
}
}
// returns the number of space characters used in the common phrase
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces) {
for (int i = 0; i < sPhrase.length(); i++) {
if (tmpArr[i] != ' ') {
tmpArr[i] = '?';
} else {
tmpArr[i] = ' ';
spaces++;
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr) {
System.out.println("\nCommon Phrase");
System.out.println("-------------");
for (int i = 0; i < tmpArr.length; i++) {
System.out.print(tmpArr[i]);
}
}
public static boolean isVowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
public static char getConsonant(Scanner stdIn, char cGuess) {
do {
System.out.println("\nEnter a lowercase consonant guess: ");
cGuess = stdIn.next().charAt(0);
} while (isVowel(cGuess));
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess) {
do {
System.out.println("\nEnter a lowercase vowel guess: ");
vGuess = stdIn.next().charAt(0);
} while (!(isVowel(vGuess)));
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int count, int vowels, int consonants) {
for (int i = 0; i < sPhrase.length(); i++) {
if (cGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
consonants++;
}
if (vGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
vowels++;
}
}
return count & vowels & consonants;
}
public static boolean endGame(boolean gameOver, int spaces, int consonants, int vowels, String sPhrase) {
int total = spaces + consonants + vowels;
if (total == sPhrase.length()) {
return true;
}
else {
return false;
}
}
public static boolean validAnswer(String answer) {
if (answer.equalsIgnoreCase("y")) {
return true;
}
else if (answer.equalsIgnoreCase("n")) {
return true;
}
else {
return false;
}
}
}
You need to check for null.
public static boolean validAnswer(String answer) {
if (answer!=null && (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n"))) {
return true;
}
return false;
}
or an other unconventional way.
public static boolean validAnswer(String answer) {
if ("y".equalsIgnoreCase(answer) || "n".equalsIgnoreCase(answer))) {
return true;
}
return false;
}
You need to fix
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.nextLine();
if ("y".equalsIgnoreCase(answer)) {
getVowel(stdIn, vGuess);
} else if ("n".equalsIgnoreCase(answer)){
break;
}
} while (!validAnswer(answer));

Java, Program to check if a string is a palindrome

I have a Java Assignment where I have to prompt for a line input, check if its a palindrome and then say if the palindrome is made of all text, all numbers, or mixed. I haven't added the part where I check what kind of palindrome it is yet, but I need help with the code to check if it's a palindrome. The code I posted below recognizes everything as a palindrome even if it isn't. This is basic Java so I'm limited to what I used below.
import java.util.Scanner;
public class Project4{
public static void main (String [] args)
{
String line = getInputLine();
while (!isEmptyLine (line))
{
if (isPalindrome (line))
System.out.println ("\"" + line + "\" is a palindrome.");
else
System.out.println ("\"" + line + "\" is not a palindrome");
line = getInputLine();
}
System.out.println ("End of program");
}
public static String getInputLine ( )
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a line of input: ");
String inputline = in.nextLine();
return inputline;
}
public static boolean isEmptyLine(String str)
{
boolean truefalse;
if(str.length()==0)
truefalse = true;
else
truefalse = false;
return truefalse;
}
public static boolean isPalindrome(String str)
{
int left = 0;
int right = str.length();
boolean okay = true;
char ch1; char ch2;
while(okay && left<right)
{
ch1 = str.charAt(left);
if(!Character.isDigit(ch1)||!Character.isLetter(ch1))
left++;
else
{
ch2 = str.charAt(right);
if(!Character.isDigit(ch2)||!Character.isLetter(ch2))
right--;
else
{
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if(ch1==ch2)
{
left++;
right--;
}
else
okay = false;
}
}
}
return okay;
}
}
You need to do logical AND of the 2 checks instead of OR -
if(!Character.isDigit(ch1) && !Character.isLetter(ch1))
Use a method like the following:
boolean isPalindrome (String input) {
int strLength = input.length;
for (int i=0; i < input.length/2; ++i) {
if (input.charAt(i) != input.charAt(strLength-i)) {
return false;
}
}
return true;
}
A late answer although it might help some in the future. The method posted below doesn't use any of StringBuilder functions.
public boolean isPalindrome(String value) {
boolean isPalindrome = true;
for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
if (value.charAt(i) != value.charAt(j)) {
isPalindrome = false;
}
}
return isPalindrome;
}

Why is my code only outputing that the string is balanced

I need the following code to have a default constructor of BalancedString that initializes str to the empty string and resets a counter to 0 The class's one arguement constructor passes a string s to str and resets counter to zero. The BalancedString class also provides a boolean method which is boolean balanced() that returns true if a string contains a balanced amount of parenthesis
import java.util.*;
public class BalancedString {
private static String str;
public BalancedString()
{
str = "";
}
public BalancedString(String s)
{
s = "";
str = s;
}
public boolean balanced(){
return true;
}
public static void main(String[] args) {
int n = 0;
CounterFancy.setCounter(n);
Scanner input = new Scanner(System.in);
System.out.println("Enter a string that has any number of Left and right Parenthesis");
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
input.close();
}
public String getStr()
{
return str;
}
public String setStr(String s)
{
str = s;
return str;
}
}
AND the following is the other project that i got the CounterFancy classes from, but the problem is above^^ why is this only outputing that it is balanced
//Joe D'Angelo
//CSC 131-03
//Chapter 10 Programming Assignment 5a.
//Takes the user's input of whether they want the counter to be negative or positive and outputs
//10 values of the user's selected input, then restarts the counter at 0
import java.util.*;
public class CounterFancy { //I messed up the first time and had to change FancyCounter to CounterFancy that is why this is changed
private static int counter;
public CounterFancy()
{
counter = 0;
}
public CounterFancy(int n){
counter = n;
}
public static int incCounter() //inc stands for increment
{
counter++;
return counter;
}
public static int decCounter() //dec stands for decrement
{
counter--;
return counter;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Press 1 for Possitive or Press 2 for Negative");
int reply = input.nextInt();
if (reply == 1)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.incCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
if (reply == 2)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.decCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
input.close();
}
public static int getCounter()
{
return counter;
}
public static void setCounter(int n)
{
counter = 0;
}
}
You are making a couple of mistakes in your BalancedString class definition. First, the str field should not be static. By making it static, all instances share the same str field.
Second, and perhaps more critical, you are not constructing your BalancedString properly. You are setting the argument back to the empty string every time!
public BalancedString(String s) {
s = ""; // THIS LINE SHOULD NOT BE HERE!
str = s;
}
Finally, your balanced() method is simply returning true regardless of the string. You need to implement some logic here.
Regarding the main program: you need to loop through all the characters, increment for each '(' and decrement for each ')' character. Instead of this:
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
You should have a loop like this:
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(')
CounterFancy.incCounter();
else if (c == ')')
CounterFancy.decCounter();
}
There's a logic problem in this bit of code:
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
You're only searching the string once for a ( and once for a ). If the string contains both a ( and a ) in any order, the counter will always count 1, then 0, and think that the parentheses are balanced.
You need to put the counting in a loop to check whether or not the parentheses are balanced. You should loop through each of the characters and check the count at each step. The parentheses are balanced if the count is non-negative at each step and ends at 0.

Java way to check if a string is palindrome [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}

Categories