Check if character `'a'` is separated from `'b'` by three places - java

folks. I'm doing every problem on codebyte.com (I suggest website to everyone who wants to practice coding skills :)) and got stuck at this problem: return true if the characters a and b are separated by exactly ``3 places anywhere in the string at least once; else return false.
Examples:
Input = "after badly" Output = "false"
Input = "Laura sobs" Output = "true"
My code is giving me false every time I write any string when in some cases it should return true. Could smb please take a look?
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter any String: ");
String myString = kbd.nextLine();
char[] myArray = myString.toCharArray();
boolean result = false;
for(int i = 0; i < myArray.length; i++)
{
if(myArray[i] == 'a' && myArray[i+4] == 'b')
result = true;
else
result = false;
}
System.out.println(result);
}

Once you find it is true, you are going to want to print True and exit from the for loop. As of now you continue going through the string even if you find a true value!
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter any String: ");
String myString = kbd.nextLine();
char[] myArray = myString.toCharArray();
boolean result = false;
for(int i = 0; i < myArray.length; i++)
{
if(myArray[i] == 'a' && myArray[i+4] == 'b'){
result = true;
break;
}
}
System.out.println(result);
}
Also it is unclear if you are looking for strings like "adddb" or "addb"
because the former is i+4 and the latter is i+3

A simple break statement will help you here. In your for loop, just place in under the if condition right after you set the result to true. If we find the case where there is 3 spaces between 'a' and 'b' we want to get out of the loop and tell the user! The break statement will automatically terminate the loop for you.
for(int i = 0; i < myArray.length; i++){
if(myArray[i] == 'a' && myArray[i+4] == 'b'){
result = true;
break;
}
else
result = false;
}

i+4 is four spaces, if you want three use i+3. Also, check the length - 3. Also, break; if you set result to true (or the next iteration will reset it). Like
boolean result = false;
for(int i = 0; i < myArray.length - 3; i++) {
if (myArray[i] == 'a' && myArray[i+3] == 'b') {
result = true;
break;
}
}

If you play with array index you might end with arrayIndexOutOfBoundException. Rather use regular expressions
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter any String: ");
String myString = kbd.nextLine();
boolean result = false;
if(myString.matches("^(.)*(a)(.){3}(b)(.)*$")){
result = true;
}
System.out.println(result);
}

Related

How can I count with indexOf in Java?

I want to replace from String and print how many times it replaced.
for examples)
Input : aabba
from : aa
to : bb
ddbba
replaced : 1
Input : AAccaabbaaaaatt
from : aa
to : bb
ddccddbbddddatt
replaced : 4
I have a problem here:
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1; // this part!
} else
continue;
} // for
My teacher said just use .indexOf and .replace, and .toLowerCase.
She gave some examples and they always replace two letters to two letters.
That's the reason why I put '+1' to find another letter.
If I remove that '+1', it counts 'aaa' twice.(aa a and a aa. And it replaced to 'dda', so it's wrong.)
But this time when I replace only one letter(ex.a), it counts less numbers than actually it has to be.(ex.'aaa' counts just two times.)
With the examples from teacher, it works well cuz all of them replace two letters.
But I want to improve this.
Here is all of my code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Input : ");
String input = scan.next();
System.out.print("from : ");
String curStr = scan.next();
System.out.print("to : ");
String chStr = scan.next();
String inputL = input.toLowerCase();
String curStrL = curStr.toLowerCase();
String chStrL = chStr.toLowerCase();
String output = inputL.replace(curStrL, chStrL);
int cnt = 0;
if (inputL.indexOf(curStrL) == -1) {
System.out.println("Do it again");
} else
System.out.println(output);
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1;
// *** to make the code find from the next letter! ***
} else
continue;
} // for
if (cnt > 0)
System.out.println("replaced : " + cnt);
else
{System.out.println("can't replace. Do it again");
break;}
System.out.println("----------------");
} // while
} // main
Just increase the counter variable of your loop with the lenght of the string to be replaced.
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i)); // EDIT by Shraft
i = i + curStr.length() - 1; // EDIT
// *** to make the code find from the next letter! ***
} else
continue;
} // for

Suggestions to improve code about primes?

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

How to get correct output for Pig Latin translator using JAVA

I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray

Program for password validation

I want to write a program that checks the inserted password for:
Length is minimum of 8
At least 1 uppercase letter
At least 1 lowercase letter
At least 3 digits
I wrote this program, but it doesn't give me the right output:
import java.util.Scanner;
public class Question5 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter your password: ");
String input = in.nextLine();
boolean flag = validate(input);
if (flag = true) {
System.out.println("password verified");
}
else {
System.out.println("not a good password");
}
}
public static boolean validate(String input) {
boolean flag = false;
int uppercaseCounter = 0;
int lowercaseCounter = 0;
int digitCounter = 0;
int letterCounter = 0;
for (int i = 0; i<(input.length()); i++) {
int totalCounter = digitCounter + letterCounter;
if (totalCounter >= 8 && digitCounter >= 3 && uppercaseCounter > 0 && lowercaseCounter > 0) {
flag = true;
}
else {
if (Character.isDigit(i)) {
digitCounter++;
}
if (Character.isLetter(i)) {
letterCounter++;
}
if (Character.isUpperCase(i)) {
uppercaseCounter++;
}
if (Character.isLowerCase(i)) {
lowercaseCounter++;
}
}
}
return flag;
}
}
Can someone help me with this? Thank you very much!
Here is the catch:
if (flag = true)
{
System.out.println("password verified");
}
= is an assignment operator == is the relational operator. To fix, do flag==true.
Also, in your method, you are comparing i, which is the counter, and not the
char At i. So do this
if(Character.isDigit(input.charAt(i))){ //Do this for all Character.isSomething() Methods
for all the checks you make.
You are actually checking the i counter in your various if instead of the input string...
use something like
char c = s.charAt(i);
and check the input chars
moreover you should change the check if(flag = true) with if(flag)
Change
if (flag = true)
{
System.out.println("password verified");
}
else
{
System.out.println("not a good password");
}
to
if (flag)
{
System.out.println("password verified");
}
else
{
System.out.println("not a good password");
}
When you write if(flag=true) then you are doing an assignment operation and not an equality comparison.
Also, the logic should be Character.isDigit(input.charAt(i)) since you want to check the character at i and not i itself.
To conclude, I would like to say that this problem would be fun to solve with Regular Expressions. Check this tutorial on regular expressions in Java.
In addition to other answers, this code should be moved below the counter increments:
int totalCounter = digitCounter + letterCounter;
if (totalCounter >= 8 && digitCounter >= 3 && uppercaseCounter > 0 && lowercaseCounter > 0) {
flag = true;
}
Otherwise, you run the risk of returning false when your password would become valid on the last character.

In need to create a java program that uses a loop to check if a password is correct. The program runs but the output isn't correct [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 8 years ago.
Improve this question
Any time I enter a password whether it is in valid format or invalid format, it always outputs "Invalid password".
import java.util.Scanner;
public class PasswordTest
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
boolean length = true;
boolean digit = true;
boolean lowercase = true;
boolean uppercase = true;
char ch = 0;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
if (s1.length()>=8){
length = true;
}
}
if (digit==false && lowercase==false && uppercase==false && length==false)
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
You need to first set all the boolean values to false at the time of declaration, and then in the code below set it to true only if it satisfies the condition. Also while printing "Valid Password" check if all boolean values are true, else print "Invalid Password". Checking if string length is greater than 8 should be outside the loop body. Following code works.
import java.util.Scanner;
public class PasswordTest
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
boolean length = false;
boolean digit = false;
boolean lowercase = false;
boolean uppercase = false;
char ch=0;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
}
if (s1.length()>=8){
length = true;
}
if (digit==true && lowercase==true && uppercase==true && length==true)
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
What you did is first set the boolean value to true then again in loop you are setting it to true which doesnot makes sense.I think this code will work fine for you
Scanner input = new Scanner(System.in);
boolean length = false;
boolean digit = false;
boolean lowercase = false;
boolean uppercase = false;
char ch = '\u0000';
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
if (s1.length()>=8){
length = true;
}
}
if (digit==true && lowercase==true && uppercase==true && length==true)
System.out.println("Valid password");
else
System.out.println("Invalid password");
For the future, I think regular expressions would be helpful.
Your password requirements seem to be "8 or more characters in length, where each character may be a lowercase letter, a capital letter, or a digit," is that right? We can express those requirements with a regular expression, such as ([a-z]|[A-Z]|[0-9]){8,}. With this, we may write
String password = input.nextLine();
if(password.matches("([a-z]|[A-Z]|[0-9]){8,}") {
// Go about your business.
}
I have a question for you, if it can't it be lowercase and if it cant be uppercase then what could it be? I made it so it has to be lowercase, here is the code (if you want it to be all uppercase then change this if statement in the code if(digit[i] == true || lowercase[i] == false || uppercase[i] == true) to if(digit[i] == true || lowercase[i] == true || uppercase[i] == false)
import java.util.Scanner;
public class PasswordTest{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
boolean length;
boolean pass = true;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
boolean[] digit = new boolean[s1.length()];
boolean[] lowercase = new boolean[s1.length()];
boolean[] uppercase = new boolean[s1.length()];
char[] ch = new char[s1.length()];
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch[i] = s1.charAt(i);
digit[i] = Character.isDigit(ch[i]);
lowercase[i] = Character.isLowerCase(ch[i]);
uppercase[i] = Character.isUpperCase(ch[i]);
}
length = s1.length()>=8;
if (length==false && s1.length() > 0) {
int i;
for(i = 0; i < s1.length(); i ++){
if(digit[i] == true|| lowercase[i] == false|| uppercase[i] == true)
pass = false;
}
if(pass == true)
System.out.println("Valid password");
else{
System.out.println("Invalid password");
}
}else{
System.out.println("Invalid password");
}
}
}

Categories

Resources