I keep encountering the error " Error: Syntax error, insert "}" to complete ClassBody" - indentation

I know there are other errors present but the main one is the bracket that is supposed to close my main method. It ask me to enter another bracket to close the class body. I have gone through many times, correctly indenting and entering in brackets to close loops and methods but it just doesn't want to work. Any ideas?
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args)
{
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber()) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator (String userInput[i]) //userInput is the array.
{
for (int i = 0; i<userInput.length; i++) {
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
}
public static boolean isNumber (String userInput[i])
{
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}
I have made quite a few changes, I knew there were other errors present. But the error I encountered from not having a correct parameter in my method was the worry. You mentioned there was still something wrong, have I tended to the syntax error you noticed?
Updated code
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args){
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i < userInput.length; i++) {
String current = userInput[i];
if (isNumber(current)) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
System.out.println(stack.toString());
}
}
}
public static boolean isOperator (String x) { //userInput is the array.
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
public static boolean isNumber (String x) {
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}

This piece of code certainly has more than just a few issues. But if you have written it entirely in your head without ever compiling it, it's actually pretty good! It shows that you think about the problem in a surprisingly correct way. I don't understand how one can get so many details wrong, but the overall structure right. And some of the syntax errors aren't really your fault: it's absolutely not obvious why it should be array.length but string.length() but at the same time arrayList.size(), it's completely inconsistent mess.
Here, I cleaned it up a bit:
import java.util.Stack;
import java.util.Scanner;
public class RPNApp {
public static void main(String[] args) {
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System. in );
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String[] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber(userInput[i])) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator(String userInput) {
for (int i = 0; i < userInput.length(); i++) {
char x = userInput.charAt(i);
if (!(x == '*' || x == '+' || x == '-' || x == '/' || x == '%')) {
return false;
}
}
return true;
}
public static boolean isNumber(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
}
return true;
}
}
Few other points to notice:
Exists-loops: Check if true, return true in loop, return false in the end.
Forall-loops: Check if false, return false in loop, return true in the end.
Chars and Strings are not the same. Chars are enclosed in single quotes and compared by ==.
It's still wrong. Think harder why. And try not to post non-compilable stuff any more.

In your function parameters you can't have userInput[i] like that. Get rid of the [i] part and then fix the rest of the other errors.

Related

Palindrome but with a scentence

So writing a palindrome with pointers and boolean. I have it working with a single word but then I began building it to work with a sentence. The problem is I am unsure how to keep the new modified sentence after making it lowercase and getting rid of the spaces for it to return whether it is or isn't a palindrome. It keeps returning the palindrome as false and when I went to check why I see that the program ignores the modification and kept the original string. I can't use "&" on the parameter as I tested it out. Any hints or takes on what I can do to keep the new modified string?
int main()
{
userInput();
return 0;
}
void userInput()
{
char str[90];
std::cout<<"Please enter a string to check if it is a palindrome: ";
std::cin.getline(str, 90);
modifyString(str);
}
void modifyString(char *string)
{
int count = 0;
for (int i=0; i<strlen(string); i++)
{
putchar(tolower(string[i]));
}
for (int i = 0; string[i]; i++)
{
if (string[i] != ' ')
{
string[count++] = string[i];
}
}
string[count] = '\0';
std::cout<<string<<std::endl;
results(string);
}
bool checkPalindrome(char *string)
{
char *begin;
char *end;
begin = string;
end = (string + strlen(string)-1);
while(begin != end)
{
if ((*begin) == (*end))
{
begin ++;
end--;
}
else
{
return false;
}
}
return true;
}
void results(char *string)
{
bool isItPalindrome;
isItPalindrome = checkPalindrome(string);
if( isItPalindrome == true)
{
std::cout<<"\nCongrats, the string is a palindrome!";
}
else
{
std::cout<<"\nThis string is not a palindrome.";
}
}
For starters this definition of main
int main()
{
userInput();
return 0;
}
does not make a sense. According to the function name main the function should perform the main task that is to output whether the entered sentence is a palindrome or not.
This for loop
for (int i=0; i<strlen(string); i++)
{
putchar(tolower(string[i]));
}
does nothing useful. It just outputs the string in the lower case.
This statement
end = (string + strlen(string)-1);
can invoke undefined behavior if an empty string was passed.
This while loop
while(begin != end)
{
if ((*begin) == (*end))
{
begin ++;
end--;
}
else
{
return false;
}
}
also can invoke undefined behavior for a string containing an even number ofo characters because after this if statement
if ((*begin) == (*end))
{
begin ++;
end--;
}
if the two adjacent characters are equal then begin after incrementing will be greater than end after its decrementing. And as a result the loop will continue its iteration.
In general the approach when the original string is changed is just a bad approach.
Your program has too many functions. It is enough to write one function that will determine whether the passed string is a palindrome or not.
Here is a demonstrative program.
#include <iostream>
#include <cstring>
#include <cctype>
bool checkPalindrome( const char *s )
{
const char *t = s + std::strlen( s );
do
{
while ( s != t && std::isspace( ( unsigned char )*s ) ) ++ s;
while ( s != t && std::isspace( ( unsigned char )*--t ) );
} while ( s != t &&
std::tolower( ( unsigned char )*s ) == tolower( ( unsigned char ) *t ) &&
++s != t );
return s == t;
}
int main()
{
const size_t N = 100;
char s[N] = "";
std::cout << "Please enter a string to check if it is a palindrome: ";
std::cin.getline( s, N );
std::cout << '\n';
if ( checkPalindrome( s ) )
{
std::cout << "Congrats, the string is a palindrome!\n";
}
else
{
std::cout << "This string is not a palindrome.\n";
}
return 0;
}
Its output might look like
Please enter a string to check if it is a palindrome: 1 23 456 6 54 321
Congrats, the string is a palindrome!
Okay, I solved it!
As one of the users on here brought up a point that my lowercase did not modify the string and only prints it out. I try my best to solve the problem and I think I found the solution and everything works perfectly fine. comment back to debug it if you like to see how it looks but what I did was create a for loop again for the lower case but made another pointer with it. here how it looks.
for (char *pt = string; *pt != '\0'; ++pt)
{
*pt = std::tolower(*pt);
++pt;
}
Now that definitely changes the string into a lower case and keeps it as a lower case.
so now the modified function looks like this and ready to take any sentence palindrome you give it. Example: A nUt fOr a jAr of tUNa. We make this all lowercase and take out space and boom palindrome and return true.
void modifyString(char *string)
{
int count = 0;
for (char *pt = string; *pt != '\0'; ++pt)
{
*pt = std::tolower(*pt);
++pt;
}
for (int i = 0; string[i]; i++)
{
if (string[i] != ' ')
{
string[count++] = string[i];
}
}
string[count] = '\0';
//take out the forward slash below to see how it looks after being modified
// std::cout<<std::endl<<string<<std::endl;
results(string);
}

Pangram String Error On My Hackerrank Code

I found this question on Hackerrank where I have to write a method to say whether or not a given string is a pangram. A sentence is a pangram if it contains all 26 letters of the alphabet. The input will only contain characters that are alphabetical (uppercase or lowercase) and spaces.
Here's the code I've gotten so far, where I use a set to keep track of which letters are present in the string. However, the code just keeps running infinitely in the while loop below.
string pangrams(string s) {
set<char> set{};
int i=0;
while (i!=s.length()) {
if(s[i]!='\0') {
set.insert(tolower(s[i]));
}
}
if (set.size() == 27) {
return "pangram";
} else {
return "not pangram";
}
}
Your function needs a slight modification. Firstly, you aren't incrementing i which makes your function go into infinite loop. Other modification is explained in code below -
string pangrams(string s) {
set<char> set{};
int i=0;
while (i!=s.length()) {
if(s[i]!=' ') { # if character is space, ignore it
set.insert(tolower(s[i]));
}
i++; # Main reason of runtime error - you missed incrementing i
}
if (set.size() == 26) { # 26 and not 27. There may be strings without space that are pangrams. So we wont add space into our set.
return "pangram";
} else {
return "not pangram";
}
}
Also, you don't need to check s[i]!='\0' since a c++ string isn't terminated with \0 character. Only checking i!=s.length() will be enough.
Hope this clears your issue !
You're never incrementing i, so your code will run infinitely. I would recommend a for loop for (int i = 0; i < s.length(); i ++) or a for-each loop for (char c : s)
Instead of using a set, you could also try this, where each character corresponds to an index in a bool[]
bool exists[27];
for (char c : s) {
if ('a' <= c && c <= 'z') {
exists[c - 'a'] = true;
} else if ('A' <= c && c <= 'A') {
exists[c - 'A'] = true;
} else if (c == ' ') {
exists[26] = true;
}
}
for (bool b : exists) {
if (!b) return false;
}
return true;

String Comparison without compare()

I'm currently doing an assignment that requires us to create our own library for string comparison without using compare(), etc.
I got it to work, but during my research I created a bool function for character compare and return values.
It needs to work as if it returns like compare(), where 0 = strings are equal and 0 > or 0 < for not equal instead of true or false like I currently set it up to be.
I tried to change the bool functions to int but now when I run the program that was correctly returning strings are equal, it's showing not equal.
Header code:
bool compare_char(char &c1, char &c2)
{
if (c1 == c2)
return true;
else if (toupper(c1) == toupper(c2))
return true;
else
return false;
}
bool insensitive_string_comparision(string &string_one, string &string_two)
{
return ((string_one.size() == string_two.size()) &&
equal(string_one.begin(), string_one.end(), string_two.begin(), &compare_char));
}
string remove_spaces(string string)
{
string.erase(remove(string.begin(), string.end(), ' '), string.end());
return string;
}
string remove_punctuation(string string)
{
for (size_t i = 0, len = string.size(); i < len; ++i)
{
if (ispunct(string[i]))
{
string.erase(i--, 1);
len = string.size();
}
}
return string;
Int header changes
int compare_char(char &c1, char &c2)
{
if (c1 == c2)
return 0;
else if (toupper(c1) == toupper(c2))
return 0;
else if (toupper(c1) > toupper(c2))
return -1;
else if (toupper(c1) < toupper(c2))
return 1;
}
int insensitive_string_comparision(string &string_one, string &string_two)
{
return ((string_one.size() == string_two.size()) &&
equal(string_one.begin(), string_one.end(), string_two.begin(), &compare_char));
}
Int main changes
int result = insensitive_string_comparision(string_one, string_two);
if (result == 0)
cout << "Both Strings are equal." << endl;
else (result == 1 || result == -1)
cout << "Both Strings are not equal." << endl;
return 0;
I feel like I'm going to have to redesign the entire function to return the value that is similar to compare().
I'm assuming bool was the wrong decision to begin with? Where should I go moving forward to return a correct value?
In your question you are not entirely clear about how you want to compare the strings, but I made some assumptions based on your example code. You can fix your problem by writing insensitive_string_comparision like:
int insensitive_string_comparision(string &string_one, string &string_two) {
int len_one = string_one.length();
int len_two = string_two.length();
int len_comparison = 0;
if (len_one > len_two) {
len_comparison = -1;
} else if (len_one < len_two) {
len_comparison = 1;
}
int minlen = (len_comparison == -1) ? len_one : len_two;
for (int i = 0; i < minlen; i++) {
int order = compare_char(string_one[i], string_two[i]);
if (order != 0) {
return order;
}
}
return len_comparison;
}
I'd also recommend turning on warnings on your compiler. You don't need to put some of your return statements in else blocks.

Checking a "password" string for space and returning true if found: C++

I am new to C++ and am working on a basic username and passsword program in C++ that uses vectors. Currently I am stuck on a function that checks a password string for a space and returns true if this happens. I was trying to implement isspace() but could not figure out if it was checking my string "password" or not. Thank you in advance for taking the time to review and help in any way. I apologize in advance if I am lacking any key information.
bool checkSpaces (string password) {
for (int i = 0; i < password.length(); i++) {
if (isspace(i)) {
return true;
} else {
return false;
}
}
By the way, I changed your isspace() to use the password string and not the loop index. This is probably a typo.
Because you have the else clause, the loop executes only once, either the first character is a space and it returns true, else it returns false.
Try with pen and paper.
bool checkSpaces (string password) {
for (int i = 0; i < password.length(); i++) {
if (isspace(password[i])) {
return true;
}
/* --> */ else {
return false;
}
}
The content of the loop says that if the character is not a space, return false. So when it hits a non-space character, it returns, regardless of how many characters have been examined.
Remove the else statement:
bool checkSpaces (string password) {
for (int i = 0; i < password.length(); i++) {
if (isspace(password[i])) {
return true;
}
}
// If the for loop terminates, and gets here,
// there were no spaces.
return false;
}

String comparison with struct element

I have piece of code like this in .c file, which detects, whether the tPerson.name is equal to one of the elements of const char* names[COUNT] or not:
define COUNT 3
...
typedef struct {
int age;
char *name;
} tPerson;
const char* names[COUNT] = {
"xxx", "yyy", "zzz"
};
....
char string[128];
strcpy(string, tPerson.name);//tPerson.name is already initizialed
int counter = 0;
while (counter != COUNT) {
if (strcmp(names[counter], string) == 0) {
counter++;
return 0;
}
}
...
All needed libraries are included. Compiler doesnt detect any errors or warnings, but program isnt working as it should - it does nothing after executing. This piece of code is only a part of the huge program, so I'd like to know, whether this construction is correct and somewhere else in the program is error or not. Thanks
You want to continue the loop if there's no match. Put the statement counter++; outside the if statement:
while (counter != COUNT) {
if (strcmp(names[counter], string) == 0) {
return 0;
}
counter++;
}
And use size_t for counter instead of int: size_t counter = 0;
You have return 0 before increasing the counter
if (strcmp(names[counter], string) == 0) {
return 0;
counter++;
}