import java.util.*;
public class Pemdas {
public static double Express(String str)
{
Stack<Double> num = new Stack<Double>();
Stack<String> op = new Stack<String>();
String number = "[0-9]*"; // any digit from 0-9
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i,i+1).equals(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
else if (str.substring(i, i+1).equals("+"))
op.push(str.substring(i, i +1));
System.out.println(str);
}
double n = num.pop();
if (op.pop().equals("+"))
n = n + num.pop();
return n;
}
public static void main(String[] args)
{
System.out.print("Enter an Expression: ");
String ex = StdIn.readString(); // This is where I enter my string input
System.out.println(Express(ex));
}
}
Let's say that I have an String variable of "5 + 5" as my input. In the for loop, the 5 is supposed to be pushed into the num stack, but I keep getting an ESE and I don't understand why.
You're using equals() when you want to match against a regex. equals() is for comparing literal strings. You likely want matches():
if (str.substring(i,i+1).matches(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
In fact, you don't need a regex at all here. You can simplify your loop by doing something like:
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (Character.isDigit(c))
num.push((double) (c - '0'));
else if (c == '+')
op.push("+");
System.out.println(str);
}
Finally, please follow Java's naming conventions and call your method express() instead of Express().
Related
This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 months ago.
I am doing an assignment for my Java class that requires me to write a program that displays the number of uppercase letters in a string. I am getting the error on my line 26 (for (int i = 0; i < ch[].length; i++){) any help would be appreciated.
import java.util.Scanner;
public class Uppercase{
public static void main(String[] args){
char[] newWord;
Scanner userWord = new Scanner(System.in);
System.out.println("Enter a word");
String word = userWord.nextLine();
System.out.println("There are " + newWord.numUppercase(word) + "uppercase letters");
}
public int numUppercase(String s){
char[] ch = new char[s.length()];
for (int i = 0; i < s.length(); i++){
ch[i] = s.charAt(i);
int uppercase = 0;
for (int i = 0; i < ch[].length; i++){
if(ch[i].valueOf() > 64 && ch[i].valueOf() < 91){
uppercase++;
}
}
return uppercase;
}
}
}
Your bug-fixed class:
public class Uppercase{
public static void main(String[] args){
Scanner userWord = new Scanner(System.in);
System.out.println("Enter a word");
String word = userWord.nextLine();
System.out.println("There are " + numUppercase(word) + "uppercase letters");
}
public static int numUppercase(String s){
char[] ch = new char[s.length()];
for (int i = 0; i < s.length(); i++){
ch[i] = s.charAt(i);
int uppercase = 0;
for (int j = 0; j < ch.length; j++){
if(ch[j] > 64 && ch[j] < 91){
uppercase++;
}
}
return uppercase;
}
return 0;
}}
Aside from the typo, the calculation of the uppercase letters is incorrect.
First, there's no need to create ch array, copy the characters from the input string, and then check the chars in ch array.
Second, an assumption that the uppercase letters reside in the range [65, 90] is applicable only to English letters. There are several Character::isUpperCase methods to check if a character or a Unicode codepoint is upper case. Character::isUpperCase(char c) has been existing for a while since Java 1.0.
So, that being said, an example counting uppercase letters could be as follows:
public static int numUpperCase(String s) {
int num = 0;
if (s != null) {
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) num++;
}
}
return num;
}
A oneliner using Stream API:
static int numUpperCase(String str) {
return Optional.ofNullable(str)
.map(s -> (int) s.chars().filter(Character::isUpperCase).count())
.orElse(0); // if input string is null
}
Notice: I know that there are tons of ways to make this simpler, but it is not allowed. I am bounded to plain, basic java, loops and hand written methods.
Even arrays are not allowed.Regex as well.
Task is to check for numbers in each word of a sentence,find the word with the greatest number which is at the same time POWER OF 3.
I did everything here and it works fine until I enter something like this.
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125
I receive output 64 instead of 125, because it stops checking when it reaches first number WHICH IS NOT POWER OF 3.
How can I continue the iteration till the end of my sentence and avoid stopping when I reach non power of 3 number ,how to modify this code to achieve that ?
Edit: But if I enter more than one word after the one that FAILS THE CONDITION, it will work just fine.
for instance:
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216
Here is my code:
public class Nine {
static int num(String s) { // method to change string to int
int b = 0;
int o = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char bi = s.charAt(i);
b += (bi - '0') * (int) Math.pow(10, o);
o++;
}
return b;
}
static boolean thirdPow(int a) {
boolean ntrec = false;
if (Math.cbrt(a) % 1 == 0)
ntrec = true;
return ntrec;
}
static int max(int a, int b) {
int max= 0;
if (a > b)
max= a;
else
max= b;
System.out.print(max);
return max;
}
static String search(String r) {
String current= ""; // 23aa64
String currentA= "";
String br = ""; // smjestamo nas broj iz rijeci 23
int bb = 0; // nas pretvoreni string u broj
int p = 0;
for (int i = 0; i < r.length(); i++) {
current+= r.charAt(i);
if (r.charAt(i) == ' ') {
for (int j = 0; j < current.length(); j++) {
while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
br += current.charAt(j);
j++;
}
bb = num(br);
System.out.println("Third pow" + thirdPow(bb));
if (thirdPow(bb)) {
p = max(p, bb);
}
br = "";
}
current= "";
}
}
String pp = "" + p;
String finalRes= "";
for (int u = 0; u < r.length(); u++) {
currentA+= r.charAt(u);
if (r.charAt(u) == ' ') {
if (currentA.contains(pp))
finalRes+= currentA;
currentA= "";
}
}
System.out.println(p);
return finalRes;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter sentence: ");
String r = scan.nextLine();
System.out.println("Our string is : " + search(r));
}
}
I am assuming that each word is separated by an empty space and containing non-Integers.
Usage of regular expressions will certainly reduce the code complexity, Let's try this code: -
String input = "asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125";
String[] extractWords = r.split(" "); //extracting each words
int[] numbers = new int[extractWords.length]; // creating an Integer array to store numbers from each word
int i=0;
for(String s : extractWords) {
numbers[i++] = Integer.parseInt(s.replaceAll("\\D+", "")); // extracting numbers
}
Now, the "numbers" array will contain [8, 27, 64, 333, 125]
You can use your logic to find a maximum among them. Hope this helps.
You can just do what I am doing. First split the sentence to chunks of words. I am doing it based on spaces, hence the in.split("\\s+"). Then find the numbers from these words. On these numbers check for the highest number only if it is a power of 3.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean isPowOfThree(int num)
{
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
String[] words = in.split("\\s+");
String maxWord = ""; //init default word
int maxNum = -1; //init default num
for(String word : words)
{
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(word);
while (m.find())
{
String num = m.group();
if(isPowOfThree(Integer.parseInt(num)))
{
if(Integer.parseInt(num) > maxNum)
{
maxNum = Integer.parseInt(num);
maxWord = word;
}
}
}
}
if(maxNum > -1)
{
System.out.println("Word is : " + maxWord);
}
else
{
System.out.println("No word of power 3");
}
}
}
The problem can be solved using \\d+ regular expression with Matcher and Pattern API in Java.
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String i = "asdas8 dasjkj278 asdjkj64 asdjk333 asdjkj125";
Matcher matcher = Pattern.compile("\\d+").matcher(i);
List<Integer> numbers = new ArrayList<>();
while (matcher.find()){
numbers.add(Integer.parseInt(matcher.group()));
}
Collections.sort(numbers);
Collections.reverse(numbers);
Integer power3 = 0;
for (Integer n : numbers) {
if (isPowOfThree(n)) {
power3 = n;
break;
}
}
System.out.println(power3);
}
static boolean isPowOfThree(int num) {
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
}
Upon using \\d+ regular expression we get all the digits in the given string for every iteration of while(matcher.find()). Once we collect all the numbers in the given string, we need to reverse sort the collection. If we iterate over this collection, the first number that we find is the largest number which is a power of 3, since the collection is already sorted in descending order.
Brother use
*string.split(" ");*
to form an array of strings and then iterate through the array and parse the numbers using regex
^[0-9]
or
\d+
and then find the biggest number from the array as simple as that. Brother proceeds step by step then your code will run faster.
my code should prompt the user to enter a string and a character, and tell where the character is located
for instance
"Welcome" and "e"
returns
"2, 7"
How can my code be fixed? Code is here. Thanks in advance (this is not homework, but some hint could be useful anyway if you don't want to post a solution).
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter a string and a character");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
char ch = input.next().charAt(0);
System.out.println(count(ch));
}
public static int count (String s, char a) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == a) {
count++;
}
}
return count;
}
}
Some mistakes:
Your code doesn't compile. Call:
System.out.println(count(s, ch));
instead of
System.out.println(count(ch));
You count the number of appearances. Instead, you should keep the indexes. You can use a String or you can add them to a list / array and convert it later to what you want.
public static String count(String s, char a) {
String result = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == a) {
result += (i+1) + ", ";
}
}
return result.substring(0, result.length() - 2);
}
I used i+1 instead of i because the indexes start at 0 in Java.
I also returned the string result.substring(0, result.length() - 2) without its last 2 characters, because I added , after every character.
Since Java 8, you can do this by using streams:
public static String count(String s, char a) {
return IntStream.range(0, s.length())
.filter(i -> a == s.charAt(i)).mapToObj(i -> i + "")
.collect(Collectors.joining(", "));
}
This code will print indexes of your Character, seprated by comma.
For more about streams, you can read here, in Java 8 documentation.
Just Change the count method :
public static ArrayList<Integer> count(String s, char a) {
ArrayList<Integer> positions = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == a) {
positions.add(i+1);
}
}
return positions;
}
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.
Alternately display any text that is typed in the textbox
// in either Capital or lowercase depending on the original
// letter changed. For example: CoMpUtEr will convert to
// cOmPuTeR and vice versa.
Switch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e )
String characters = (SecondTextField.getText()); //String to read the user input
int length = characters.length(); //change the string characters to length
for(int i = 0; i < length; i++) //to check the characters of string..
{
char character = characters.charAt(i);
if(Character.isUpperCase(character))
{
SecondTextField.setText("" + characters.toLowerCase());
}
else if(Character.isLowerCase(character))
{
SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
}
}}
});
setText is changing the text content to exactly what you give it, not appending it.
Convert the String from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).
Example, start with A. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.
You can use StringUtils.swapCase() from org.apache.commons
This is a better method :-
void main()throws IOException
{
System.out.println("Enter sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String sentence = "";
for(int i=0;i<str.length();i++)
{
if(Character.isUpperCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)+32);
sentence = sentence + ch2;
}
else if(Character.isLowerCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)-32);
sentence = sentence + ch2;
}
else
sentence= sentence + str.charAt(i);
}
System.out.println(sentence);
}
The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.
As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.
You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.
String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();
This is a better approach without using any String function.
public static String ReverseCases(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char temp;
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
temp = (char)(str.charAt(i) - 32);
}
else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
temp = (char)(str.charAt(i) + 32);
}
else {
temp = str.charAt(i);
}
sb.append(temp);
}
return sb.toString();
}
Here you are some other version:
public class Palindrom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word to check: ");
String checkWord = sc.nextLine();
System.out.println(isPalindrome(checkWord));
sc.close();
}
public static boolean isPalindrome(String str) {
StringBuilder secondSB = new StringBuilder();
StringBuilder sb = new StringBuilder();
sb.append(str);
for(int i = 0; i<sb.length();i++){
char c = sb.charAt(i);
if(Character.isUpperCase(c)){
sb.setCharAt(i, Character.toLowerCase(c));
}
}
secondSB.append(sb);
return sb.toString().equals(secondSB.reverse().toString());
}
}
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
Methods description:
*toLowerCase()* Returns a new string with all characters converted to lowercase.
*toUpperCase()* Returns a new string with all characters converted to uppercase.
For example:
"Welcome".toLowerCase() returns a new string, welcome
"Welcome".toUpperCase() returns a new string, WELCOME
If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.
A = 1000001 a = 1100001
B = 1000010 b = 1100010
C = 1000011 c = 1100011
D = 1000100 d = 1100100
...
Z = 1011010 z = 1111010
So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.
Look at the below code for simply changing the string case without using any if-else conditions.
public final class ChangeStringCase {
public static void main(String[] args) {
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
char ans = (char)(str.charAt(i) ^ 32);
System.out.print(ans); // Final Output: hELLO wORLD
}
}
}
Time Complexity: O(N) where N = Length of the string.
Space Complexity: O(1)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String satr=scanner.nextLine();
String newString = "";
for (int i = 0; i < satr.length(); i++) {
if (Character.isUpperCase(satr.charAt(i))) {
newString+=Character.toLowerCase(satr.charAt(i));
}else newString += Character.toUpperCase(satr.charAt(i));
}
System.out.println(newString);
}
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isUpperCase(ch[i])) {
ch[i] = Character.toLowerCase(ch[i]);
} else {
ch[i] = Character.toUpperCase(ch[i]);
}
}
System.out.println(ch);
}
}
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
String str1,str2;
Scanner S=new Scanner(System.in);
str1=S.nextLine();
System.out.println(str1);
str2=S.nextLine();
str1=str1.concat(str2);
System.out.println(str1.toLowerCase());