Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a question on parser, whenever a user enters the expression like (a+b*c(d-e), He forgot to enter the other closing brace, and the program should give an error like It's a wrong Expression. Please help me out in doing this program, I have no idea how to start.
Use a stack data structure to validate the parenthesis matching.
If the character is '(','{','[' push the character onto the stack if the character is ')','}',']' respectively for the matching opening bracket then pop. Continue this till the stack is empty.
Code:
import java.util.*;
class ParenthesisMatching
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
System.out.println("Enter expression");
String exp = scan.next();
if(isValid(exp))
System.out.println("matched");
else System.out.println("unmatched");
}
public static boolean isValid(String s) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to write a code in Java which does make changes to case of a alphabet character in an alternating fashion(either make it lowercase or uppercase)
For Example:
changeCapitalization("hey 123 ABC idk"); // hEy 123 AbC iDk
changeCapitalization("abcdef ghijk 12 abc"); // aBcDeF gHiJk 1 AbC
You can use StringBuilder to build new string and boolean marker to change between lower/upper letter case.
public static String changeCapitalization(String str) {
StringBuilder buf = new StringBuilder(str.length());
boolean upperCase = false;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
buf.append(upperCase ? Character.toUpperCase(ch) : Character.toLowerCase(ch));
upperCase = !upperCase;
} else
buf.append(ch);
}
return buf.toString();
}
public static void main(String[] args) {
String str ="hello THERE";
String new_str="";
for(int i=0;i<str.length();i++){
String c =Character.toString(str.charAt(i));
if(Character.isUpperCase(str.charAt(i))){
c=c.toLowerCase();
new_str+=c;
}
else if(Character.isLowerCase(str.charAt(i))){
c=c.toUpperCase();
new_str+=c;
}
else if(c.equals(" ")){
new_str+=" ";
}
}
System.out.println(str);
System.out.println(new_str);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm new for Java,and I want to know can we increase the variable value through charAt() in java as below.
public class CheckPalindrome{
public static boolean isPalindrome(String text) {
int length = text.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = text.charAt(forward++);
char backwardChar = text.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
public static void main(String args[]){
System.out.println (isPalindrome("level"));
}
}
I want to know what is happening below code line..
char forwardChar = text.charAt(forward++);
String is immutable, so no you can't do that. You need to create a new string (e.g. with substring) and combine the results:
String text = "ABCCEFG";
char midCharacter = text.charAt(3);
midCharacter++;
String output = text.substring(0, 3) + midCharacter + text.substring(4);
Output:
ABCDEFG
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to make a ReverseString program. It's only returning one word only. I would like a full sentence.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = input.next();
String reverse = "";
for (int i = word.length() - 1; i >= 0; i--)
reverse += word.charAt(i);
System.out.println(reverse);
}
}
You can use the reverse method of the StringBuilder/StringBuffer class.
Something like :
String reversedString = new StringBuilder(input.nextLine()).reverse().toString();
Or if you want a more low-level approach you could use a Stack push every character in it and pop it one by one to get the reversal of it.
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
stringBuilder.append(stack.pop());
}
return stringBuilder.toString();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
It is an android app.
Text is stored in an array. It should change serial wise
Here is what I had done before.
String name = "";
String names[] = {"A", "B", "C", "D"};
int counter = 0;
name = names[counter];
counter++;
if(counter >= 3)
{
counter = 0;
}
return name;
I was doing something like that before. I know it totally incorrect . But something like this I wanted to do.
This may help solve your problem.
import java.util.Scanner;
public class Main {
static int currentIndex = 0;
static String[] words = {"word1", "word2", "word3"};
public static void main(String[] args) {
while(true) {
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input != null){
System.out.println(words[currentIndex++]);
if(currentIndex == words.length){
currentIndex = 0;
}
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
//This program determines if the input string is a palindrome
import java.util.*;//importing all the methods from java.util class
import static java.lang.System.out;
public class Pallindrome {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input= new Scanner(System.in);
String pallindrome;
out.println("Enter a string: ");
pallindrome= input.nextLine();
ArrayList<String> pall= new ArrayList<String>();
buildAL(pall, pallindrome);
display(pall);
if(isPalendrome(pall))
out.println(pallindrome + " is a pallindrome");
else
out.println(pallindrome + " is not a pallindrome");
}
static void display(ArrayList<String> arr1){ //this method is for displaying the array list
for(int i=0; i<arr1.size();i++)
out.print(arr1.get(i));
out.println();
}
static void buildAL(ArrayList<String> arr2, String word){ //this is for building the array with the entered word
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
static Boolean isPalendrome(ArrayList<String> arr3){ //it will test if the word is pallindrome
ArrayList<String> rarr3= new ArrayList<String>();
rarr3.addAll(arr3);
Collections.reverse(rarr3);
for(int i=0;i<rarr3.size();i++)
if(!(rarr3.get(i).equals(arr3.get(i))))
return false;
return true;
}
}
When I run this code it shows the same output. please point out the error.
It's unclear what the problem is but your for loop doesnt over the letters in word as the termination condition is based on the empty List size passed to the buildAL method. Replace
for (int i = 0; i < arr2.size(); i++)
with
for (int i = 0; i < word.length(); i++) {
Below
static void buildAL(ArrayList<String> arr2, String word){
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
arr2.size() is 0 as you don't have any element in the list. Either add the word to the list or do word.length() in for loop.
Also, if I have to do the same thing I would do something like -
After reading the string from the scanner, Simply do
StringBuilder sb = new StringBuilder("your String");
if ("yourString".equals(sb.reverse().toString())) {
//or you can use equalsIgnoreCase also if that fits your requirement
//its a palindrome
} //Otherwise, not.