Java 'error: class expected' when usig array length method [duplicate] - java

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
}

Related

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index out of bounds

I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote

why does this method take off the last letter in the string?

This is part of a java project, we have to take in a sentence that has multiple spaces between the world (a sentence like this) and convert it into a character array, then print out the sentence without all the extra spaces. It works, but it prints out the sentence missing the last letter.
Sentence Class:
public class sentences {
String sentence;
int length;
private char[] ch;
public sentences(String sentence, int length) {
this.sentence = sentence;
this.length = length;
char [] ch;
}
/**method that takes a string and turns it into an array then prints out the array
* makes an empty string and fills it with the char, takes out empty spaces
*
*/
public char[] makesentenceanarray(String sentence, int length) {
char[] ch = new char[sentence.length()];
//String noWhite = "";
StringBuilder s = new StringBuilder();
char prevchar = ' ';
for (int i = 0; i < sentence.length(); i++) {
ch[i] = sentence.charAt(i);
}
for(int j = 0; j < sentence.length(); j++) {
char currentchar = ch[j];
if( !(prevchar == ' ' && currentchar == prevchar)) {
s.append(prevchar);
}
prevchar = currentchar;
}
s.deleteCharAt(0);
System.out.println(ch);
System.out.print(s);
return ch;
}
}
Tester class:
import java.util.Scanner;
public class tester {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
System.out.print("enter your sentence: ");
String a = scan.nextLine();
sentences s1 = new sentences(a, a.length());
s1.makesentenceanarray(a, a.length());
}
}
********************************************************************************
heres what I end up with:
enter your sentence: this is my sentence
this is my sentence
this is my sentenc
any help is appreciated thanks!
After the loop, append prevchar. Also, use StringBuilder.
You’re appending the previous character. Think instead about the circumstances under which you would append the current character. In you loop you will look at every current character, but for the very last character, the previous will be the second to last character and then the loop stops. Make sense?
sentence.length() starts counting at 1. (Yes I know it's inconsistent :D)Therefore you need to start counting at 1 and compare with <= at the first for loop.
public char[] makesentenceanarray(String sentence, int length) {
char[] ch = new char[sentence.length()];
//String noWhite = "";
StringBuilder s = new StringBuilder();
char prevchar = ' ';
for (int i = 1; i <= sentence.length(); i++) {
//you should do this now bc of the change of the for loop:
//ch[i - 1] = sentence.charAt(i - 1);
ch[i] = sentence.charAt(i);
}
for(int j = 0; j < sentence.length(); j++) {
char currentchar = ch[j];
if( !(prevchar == ' ' && currentchar == prevchar)) {
s.append(prevchar);
}
prevchar = currentchar;
}
//Now you should be able to delete this
//s.deleteCharAt(0);
System.out.println(ch);
System.out.print(s);
return ch;
}
}

Can not find out why my output is printing 2 times and how swap chars in StringBuilder

I am using a StringBuilder and appending it with * for each letter of the word to be guessed. Then when the user guesses a letter/char correct the StringBuilder should be changing the char at a certain index from * to the guessed letter/char. Then print the new StringBuilder to show the correct letter like this (ho * s *). If the guess is wrong then just print the StringBuilder and say wrong guess.
I am trying to figure out why this is not working properly. I am getting output like: (minus the / it wouldn't post just the *)
HANGMAN
Try and guess the word, you have 9 attempts:
/***************
Guess a letter: g
/*************************
Guess a letter: p
p****p****p****p****p****
Guess a letter
It is also printing the word more than once and I am not sure why.
import java.util.Random;
import java.util.Scanner;
public class Hangman {
static String[] words = {"house", "show", "garage", "computer", "programming", "porch", "dog"};
static char[] correct = new char[26];
static char[] wrong = new char[26];
static char guess;
static Random generator = new Random();
static Scanner input = new Scanner(System.in);
static String word;
static int attempts = 0;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args){
word = words[generator.nextInt(words.length)];
System.out.print("HANGMAN\nTry and guess the word, you have 9 attempts: \n");
printAstrick();
while(attempts <= 9){
System.out.print("\nGuess a letter: ");
guess = input.next().charAt(0);
findMatch(guess);
}
if(attempts == 9){
System.out.println("Your attempts are up");
}
}
public static void findMatch(char c){
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == c){
correct[i] = c;
sb.setCharAt(i, c);
System.out.print(sb.toString());
}
else if(word.charAt(i) != c){
wrong[i] = c;
sb.setCharAt(i, '*');
System.out.print(sb.toString());
}
}
attempts++;
}
public static void printAstrick(){
for(int i = 0; i < word.length(); i++){
sb.append("*");
System.out.print(sb.toString());
}
}
You are overwriting any correct guesses with this line:
sb.setCharAt(i, '*');
in your findMatch method so you should remove it.
Also, your print statements are in for loops so each word is printed out n times. Fix this by moving your calls to System.out.print(sb.toString()) outside of the for loops.
This leaves you with:
public static void findMatch(char c) {
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == c) {
correct[i] = c;
sb.setCharAt(i, c);
} else if (word.charAt(i) != c) {
wrong[i] = c;
}
}
System.out.print(sb.toString());
attempts++;
}
public static void printAstrick() {
for (int i = 0; i < word.length(); i++) {
sb.append("*");
}
System.out.print(sb.toString());
}

Java Method to find the occurencies of a certain character

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;
}

Why are my string variables not being pushed in my stacks?

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().

Categories