SimpleSymbols String in java - java

I am a beginner in java, and I have this question:
Write a java program that include method SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (i.e. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol.
Sample Test Cases:
Input:" +d+=3=+s+ "
Output:"true" //as +d+ and +s+ are surrounded by +
Input:" f++d+ "
Output:"false" // as f+ is not surround by +
here is my code:
package simplesympoles;
import java.util.Scanner;
public class SimpleSympoles {
static Scanner input= new Scanner(System.in);
public static void main(String[] args) {
for (int i = 0; i <2; i++) {
System.out.println("Enter a string: ");
String s=input.next();
System.out.println(SimpleSymbols(s));
}
}
public static boolean SimpleSymbols(String s){
String s1=s.trim();
for (int i = 0 ; i <s.length(); i++)
if (s1.charAt(i+1)=='+'&&s1.charAt(i-1)=='+' && Character.isLetter(s1.charAt(i)))
return true;
return false;
}
}
when I enter the string which is make the method returns true, it runs good, but when I enter a string that does not detect the conditions, it does not return false, but a run time error happen and I tried my best to fix it but I can't
here is my run:
Enter a string:
+d+=3=+s+
true
Enter a string:
f++d+
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range:
-1 at java.lang.String.charAt(String.java:658) at simplesympoles.SimpleSympoles.SimpleSymbols(SimpleSympoles.java:26)
at simplesympoles.SimpleSympoles.main(SimpleSympoles.java:14)
/Users/Zahraa_maher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53:
Java returned: 1 BUILD FAILED (total time: 21 seconds)
I need your assistance to solve it, and thank you very much!

With this test:
if (s1.charAt(i+1)=='+'&&s1.charAt(i-1)=='+' && Character.isLetter(s1.charAt(i)))
return true;
You're saying that if you find a letter with a + symbol either side then the string is valid. But every letter has to be surrounded by a +, so you need to switch the logic and instead do
if (Character.isLetter(s1.charAt(i)) && (s1.charAt(i-1)!='+' || s1.charAt(i+1)!='+'))
return false;
Then, if you get to the end of the string without returning false you know the string is valid and you can return true.
Also, if you want to look behind and ahead one character then you can't start at the first character or go to the last character, or you'll get a StringIndexOutOfBoundsException. Instead your loop should look like this:
for (int i = 1 ; i <s.length()-1; i++)
Obviously you do need to check the first and last characters, but we can do that right at the start, since if either of them is a letter then the string is invalid.
if(Character.isLetter(s1.charAt(0)) || Character.isLetter(s1.charAt(s1.length()-1)))
return false;
Putting this all together we get:
public static boolean SimpleSymbols(String s){
String s1=s.trim();
if(Character.isLetter(s1.charAt(0)) || Character.isLetter(s1.charAt(s1.length()-1)))
return false;
for (int i = 1 ; i <s.length()-1; i++)
if (Character.isLetter(s1.charAt(i)) && (s1.charAt(i-1)!='+' || s1.charAt(i+1)!='+'))
return false;
return true;
}

finally, I got the answer!
package simplesympoles;
import java.util.Scanner;
public class SimpleSympoles {
static Scanner input= new Scanner(System.in);
public static void main(String[] args) {
for (int i = 0; i <2; i++) {
System.out.println("Enter a string: ");
String s=input.next();
System.out.println(SimpleSymbols(s));
}
}
public static boolean SimpleSymbols(String s){
String s1=s.trim();
if(Character.isLetter(s.charAt(0)) || Character.isLetter(s.charAt(s.length()-1)))
return false;
for(int i=1;i<s.length();i++){
if(Character.isLetter(s.charAt(i)) && (s.charAt(i-1)!='+' || s.charAt(i+1)!='+'))
return false;
}
return true;
}
}

Related

Finding substring in a given string by changing into char array

i am working on the following program. but its not giving me the correct output for string "nameiskhan" and substring as"name".
i know this might be a duplicate question but i couldn't find the desired answer in those questions.
import java.util.*;
import java.lang.String;
public class CheckingSubstring2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String: ");
String string1 = input.next();
System.out.println("Please enter a second String: ");
String substring = input.next();
if (isSubstring(string1, substring)) {
System.out.println("The second string is a substring of the first.");
} else {
System.out.println("The second string is NOT a substring of the first.");
}
}
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
boolean match = true;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
match = true;
} else {
match = false;
}
}
}
return match;
}
}
As you want to do it without contains, how about this?
What I do here is that going through the original string one pass and check if the substring can be found as consecutive characters in the main String.
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
for (int i = 0; i < c.length; i++) {
if(c[i] == d[0]){
boolean match = false;
for(int j = 0; j < d.length; j++){
if(c[i+j] != d[j]){
match = false;
break;
} else{
match = true;
}
}
if(match) return true;
}
}
return false;
}
I would suggest becoming familiar with different debugging techniques. A very quick and easy one is a print statement. For example, you can print the values that you are comparing to make sure it looks reasonable. It will also give you an indication of how many times your loop is running. Stepping through the algorithm, the first two characters to be compared are c[0] = 'n' and d[0] = 'n'. That's good. The next two are c[0] = 'n' and d[1] = 'a'. That's not. Also, I assume you intend for the program to stop running if it finds a substring, but it doesn't appear that it would do so. Likewise, you might consider not comparing every element of the substring if a comparison has already been false.

Java check String input

I am trying to check an input String:
- length
- type
- special char at the end
The input is a identity card like this 24659213Q.
So what I got for now is:
public void datosUsuario() {
System.out.print("Write ID: ");
input = scanner.nextLine();
}
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9){
status = true;
System.out.println("Length: OK!");
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
}
So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.
Any ideas would be apreciated! Thank you!
I'd use a regular expression:
String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);
See String.matches and regular expression documentation.
A simple method would be:
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
if (Character.isAlphabetic(input.charAt(8)) {
status = true;
System.out.println("OK!");
} else {
status = false;
System.out.println("Length: OK, but last character must be alphabetic");
}
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
You can use reg ex,
public static void comprobacion(String input) {
status = false;
if(input.matches("\\d{8}\\w{1}"))
{
status = true;
}
}
Here, \d{8} = eight digits
\w{1} = one alphabetical character
You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:
String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
//Checks all but the last character
if( !Character.isDigit( input.charAt(c) ) ){
System.out.println("The String does not start with 8 digits");
}
}
if( Character.isDigit( input.charAt(8) ) ){
//Checks only last character
System.out.println("The String does not end with a char");
}
The method of regular expression can also be followed as mentioned above. There is one more way to do it.
1)Split the string into two -one with 8 characters and the other with last one character.
2)Parse the first String
Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.
If you don't catch the exception it is alright else it is wrong.

String matching program

I am trying to make a java program to reverse the given string and each time iterate, compare with the reversed string then to print pass if matched else fail.
My program is:
package sss;
import java.util.Scanner;
public class ssi {
/**
* #param args
*/
public static void main(String[] args) {
String original,reverse="";
Scanner sc=new Scanner(System.in);
int ascii11,ascii12,ascii13,ascii14;
System.out.println("enter the string to be reversed");
original=sc.next();
int length=original.length();
for(int i=length-1;i>=0;i--)
{
reverse=reverse+original.charAt(i);
}
System.out.println(reverse);
//System.out.println(original);
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}
// TODO Auto-generated method stub
sc.close();
}
}
here each time when the for loop iterates i am getting pass or fail for each pair of numbers but i want the o/p as to print only pass or fail ONCE.
can any one help me out please...
Example Code:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
String original;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string to be reversed: ");
original = sc.next();
int halfLength = original.length()/2;
int lastIndex = original.length() - 1;
int i;
for(i = 0; i < halfLength; i++) {
if(original.charAt(i) != original.charAt(lastIndex - i)) {
System.out.println("Fail!");
break;
}
}
// Managed to match all characters
if(i == halfLength) {
System.out.println("Pass!");
}
sc.close();
}
}
Input/Output:
Enter the string to be reversed: banana
Fail!
Enter the string to be reversed: RADAR
Pass!
Enter the string to be reversed: asdwwdsa
Pass!
So the idea is to:
Compare the first half of the string with the second half of the string
Compare the first character with the last character
Compare the 2nd character with the 2nd last character, and so on.
If any character does not match, print Fail!
If the loop finishes, it implies that the string is a palindrome (original == reversed), print Pass!
You need to flag each comparison of the original and reversed characters with either a pass or a fail boolean value. Obviously if any of them are flagged with a fail, you can then terminate the algorithm and print fail. If the for loop continues with a pass right to the end, then print pass once outside of the for loop.
Your print statement is inside the loop , so its printing "pass" or "fail" for each loop. You should use a flag to check whether all the ascii characters are same. and then check the status of flag outside the loop.
OR
Use StringBuffer it has a built-in method to reverse string.
StringBuffer input = new StringBuffer("Your String to reverse");
String reverse = input.reverse().toString();
if(input.equals(reverse))
System.out.println("pass");
else
System.out.println("fail");
Move your if condition out of for loop.
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
}
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}

Issue with Palindrome class using Stacks

I am trying to write a Palindrome class using Stacks to determine if a word entered by user is a palindrome. There seems to be an issue in my Palindrome class. Can someone please help me identify it? My program works but no matter what word I type, it returns that the word is not a palindrome.
import java.util.Stack;
public class Palindrome
{
public Palindrome()
{
Stack stack = new Stack();
String input = "";
boolean isPalindrome = false;
for(int i = 0; i < input.length(); i++)
{
stack.push(i);
}
String opposite = " ";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
if(input.equals(opposite))
isPalindrome = true;
else
isPalindrome = false;
}//end main
}//end class Palindrome
Here is my PalindromeCheck class:
import java.util.Scanner;
public class PalinDromeCheck
{
public static void main(String[] args)
{
Palindrome pal = new Palindrome();
Scanner type = new Scanner(System.in); //create scanner for user to type a word
String word = null; //initial word to check
String stop = null; //stops processing of word
do
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(pal.equals(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
System.out.println("Would you like to try another word? Type Y for 'Yes' or N for 'No'");
stop = type.nextLine(); //stops processing
}
while(stop.equalsIgnoreCase("y")); //continues to process and ignores upper or lowercase Y
}
}
You have several bugs.
First, you need to give the input to the Palindrome class.
Second, when you reverse the input using stack, you push the index on the stack, not the character.
Third, it's not a good practice to do everything une constructor. Palindrome class doesn't need to know the input as member or for initialization purpose
If you don't need to have several implementation of Palindrome, you shall use a static method.
Try this :
public class Palindrome
{
public static boolean isPalindrome(String input)
{
char[] inputArray = input.toCharArray();
bool isOk = true;
for(int i = 0; i < inputArray.length/2 && isOk; i++){
isOk &= inputArray[i] == inputArray[inputArray.length - i - 1];
}
return isOk;
} // end method
} //end class Palindrome
Then, your main function could be :
public static void main(String[] args)
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word)) {
System.out.println("is a palindrome");
} else {
System.out.println("is not a palindrome\n");
}
} // End of main
Is this your full Palindrome-Class? If yes, it has no input to handle!
public class Palindrome
{
public static boolean isPalindrome(String input)
{
Stack stack = new Stack();
for(int i = 0; i < input.length(); i++)
{
stack.push(input.charAt(i));
}
String opposite = "";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
return input.equals(opposite);
}//end main
}//end class Palindrome
this creates a static method you can use in your code like:
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
Your input is empty because you set input to "" in the constructor. You would be better off using a constructor argument to contain the input and then keep track of that using a member variable.
The code you typed is probably better suited to be in a method (equals perhaps? You will have to override this). You might want to consider pushing the character from the input string onto the stack rather then 0, 1, 2, 3... n (where n = input.length() - 1).
Your current .equals(word) does not do what you think it does because you have not provided an overload.

method declaration

I haven't been programming for long and this is my first time declaring a method within my program and using this method in the program. In its simplicity, the program has the user enter a 5 digit zipcode and the method I created checks that the zipcode is only 5 characters and is all digits. When I use the method in the program no matter what I enter for the zipcode, the while statement runs asking me to input my zipcode again. This should only happen if you enter a string thats not five characters or a string without only digits. However, right now it is happening even when an actual zipcode is entered, leaving me to assume something is wrong with the method. I tried to be as clear as possible in the question but if any further clarification is needed I can try to clear things up, any info you can give would be appreciated. Here is my code:
import java.util.Scanner;
public class BarCode {
public static void main(String[] args) {
String zipcode;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a 5 digit zipcode: ");
zipcode = in.nextLine();
while (checkInput(zipcode) == false) {
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
} // end while
} // ends main
public static boolean checkInput(String zipcode) {
boolean zipcodeLength = true;
boolean zipcodeDigits = true;
if (zipcode.length() != 5) {
zipcodeLength = false;
} // end if statement
for (int i = 0; i <= zipcode.length(); i++) {
if (!Character.isDigit(i)) {
zipcodeDigits = false;
} // end if statement
} // end for statement
if (zipcodeLength == false || zipcodeDigits == false) {
return false;
} // end if statement
else {
return true;
} // end else statement
} // end checkInput
}
This is your problem :
if(!Character.isDigit(i))
should be
if(!Character.isDigit(zipcode.charAt(i)))
import java.util.Scanner;
public class BarCode{ public static void main(String[] args){
String zipcode;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a 5 digit zipcode: ");
zipcode = in.nextLine();
while (checkInput(zipcode)==false){
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
}
}
public static boolean checkInput(String zipcode){
boolean zipcodeLength = true;
boolean zipcodeDigits = true;
if (zipcode.length() != 5){
zipcodeLength = false;
} // end if statement
for (int i=0; i<zipcode.length();i++){
if(!Character.isDigit(zipcode.charAt(i))){
zipcodeDigits = false;
}
}
return zipcodeLength && zipcodeDigits;
} // end checkInput
}
There are two problems.
The first is that you're going <= when you need to be doing <.
The second is that you need to check zipcode.charAt(i) instead of i. Checking i will check the digits 0 - 4 (5 with your code) for a 5 digit zipcode no matter what zipcode you enter.
So those two lines become
for ( int i=0; i<zipcode.length();i++){
if(!Character.isDigit(zipcode.charAt(i))){
Alternatively, I personally would code this method like this:
public static boolean checkInput(String zipcode){
if(zipcode.length() != 5) return false; // bad length
for(int i = 0; i < zipcode.length(); i++) {
if(!Character.isDigit(zipcode.charAt(i)) // bad digit
return false;
}
return true; // if no bad condition, it's good
}
while (zipcode.matches("[0-9]{5}"))==false){
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
}
public static boolean checkInput(String zipcode){
if (zipcode.length() != 5){
return false;
}
for ( int i=0; i<zipcode.length();i++){
char charAt = zipcode.charAt(i);
if(!Character.isDigit(charAt)){
return false;
}
}
return true;
}
You needed to use charAt instead of seeing if i was a digit, because obviously it will be.
!Character.isDigit(i)
That looks like a mistake to me. i is of type int:
for (int i = 0; i <= zipcode.length(); i++) {
// ...
}
So you're not calling Character.isDigit(char), you're calling Character.isDigit(int). The two methods behave differently: one deals with a text characters while the other deals with a numeric unicode value. Try this:
System.out.println("= char '1' =");
System.out.println(Character.isDigit('1')); // true
System.out.println("= int 1 =");
System.out.println(Character.isDigit(1)); // false
System.out.println("= Unicode 31h (49) =");
System.out.println(Character.isDigit('\u0031')); // true
System.out.println("= int 49 =");
System.out.println(Character.isDigit(49)); // true
And you'll get the following output:
= char '1' =
true
= int 1 =
false
= Unicode 31h (49) =
true
= int 49 =
true
You need not store the boolean value false in some boolean variable. Just return the moment you find that the zipcode is invalid.
And you should do : -
!Character.isDigit(zipcode.charAt(i))
in place of: -
!Character.isDigit(i)
So, you can modify your method like this: -
public static boolean checkInput(String zipcode){
if (zipcode.length() != 5){
return false;
}
for ( int i = 0; i < zipcode.length(); i++){
if(!Character.isDigit(zipcode.charAt(i))){
return false;
}
}
return true;
}
Also, you don't need to do :- booleanVar == false. Just do : - !booleanVar thats enough.

Categories