java: cannot find a symbol when trying to use .isDigit() [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Tried both in my IDE and in the online IDE my textbook on Zybooks.com gives me to work in. My goal is to check whether or not the variable passCode contains a digit. Here's the code:
public class CheckingPasscodes{
public static void main (String [] args) {
boolean hasDigit = false;
String passCode = "";
int valid = 0;
passCode = "abc";
if (passCode.isDigit(passCode.charAt(0)) || passCode.isDigit(passCode.charAt(1)) || passCode.isDigit(passCode.charAt(2))) {
hasDigit = true;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}
I get the error on line 9 (where the first if starts):
java: cannot find symbol
symbol: method isDigit(char)
location: variable passCode of type java.lang.String
Tried changing passCode.charAt(0) (or 1 and 2) to simply 'a' (or 'b' and 'c') to test whether it was because I was putting a method inside another method, but I seem to get the same error.
I eventually solved the problem by asking a friend, who provided me this, instead:
char s = passCode.charAt(0);
char s1 = passCode.charAt(1);
char s2 = passCode.charAt(2);
if ((s>'0' && s<'9') || (s1>'0' && s1<'9') || (s2>'0' && s2<'9')) {
hasDigit=true;
}
It makes perfect sense, and I did think of doing something similar, but the chapter in which this exercise is isn't about .charAt()—we covered that before—but rather about .isDigit() and other character operations, so doing what I did is all but cheating.
This is driving me nuts.
P.S.: I'm pretty new to Java, so, if the answer is something really obvious, I'm really sorry. And thanks for taking your time to read all this!

You're calling .isDigit() on a String object, which doesn't have such a method. It's a static method of the Character class.
Character.isDigit(passCode.charAt(0));
A big hint is that your error message stated the following:
location: variable passCode of type java.lang.String
which should automatically prompt you to look at the String class for the documentation on whatever method you're looking for - and, subsequently, to discover it doesn't have such a method.

java.lang.String doesnt have a isDigit method, that is only for Char class...
use it as
boolean hasDigit = Character.isDigit('1');

Related

How to fix this non-compiling method?

Doing some practice exam questions, and it says to:
assume the statement String pattern = getPattern();. Explain if any flow in the method getPattern(). How would you fix it?
Here's the code:
public static String getPattern() {
Scanner inPattern = new Scanner(System.in);
String pattern = " ";
boolean valid = false;
int i = 0;
while(!valid){
System.out.println("please enter a valid pattern with X or x");
pattern = inPattern.next();
if ( ! (pattern.charAt(i) == 'X' || pattern.charAt(i) == 'x'
|| pattern.charAt(i) == 'r'))
System.out.println("You have entered an invalid pattern");
else if ((i + 1) == pattern.length()) valid = true;
};
inPattern.close();
return pattern;
}
I'm not really sure how I would fix this... obviously this is a smaller part of a bigger code because this doesn't include a main method, personally making it a bit more difficult to see what's wrong.
I'm really not sure exactly what to change here. I've been up for 7+ hours watching youtube videos and attempting to understand this stuff or to do this question but I really cannot figure it out. would anyone be able to provide a good example?
Okey, so first things first. The code you recieved is all you need to run it, its not part of a "bigger program". It tells you to assume its being called like this:
String pattern = getPattern();
So when calling the method "getPattern" from a main method what happens? You get prompted to input a "valid" character, if the character is valid the method returns the character.
The question itself is weirdly designed. But looking at the code, I guess what they're fishing for is that you're being told to input the character 'x' or 'X'. But in the code another valid character is 'r'. So either they want you to change the text given to the user, or remove 'r' as a valid char would be my guess.

how to pass a variable through sendKeys in selenium webdriver?

I want to pass the float variable 'f' through sendKeys in the below program.Can someone please let me know the same? As of now, it is throwing
"The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments ".
Code:
public static String isEditable(String s1) {
f=Float.parseFloat(s1);
System.out.println(f);
boolean bool=webDriver.findElement(By.xpath("expression")).isEnabled();
if(bool) {
if((f<0) || (f>6)) {
error="Value must be between 0.00% and 6.00%";
System.out.println(error);
} else {
webDriver.findElement(By.xpath(""expression")).sendKeys(f);
}
} else {
error="Please enter a valid Number";
}
return error;
}
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
I know you already accepted an answer but I wanted to clean up your code a little and give you some feedback.
I changed the name of the function because a function named isEditable() should return a boolean indicating whether some field is editable. That's not what your function is doing so it should be given a more appropriate name. I made a guess at what the actual name should be... I could be way off but you should name it something more along the lines of what it's actually doing... putting text in a field.
I removed the isEnabled() check because that should be done in the function that sets the fund number. Each function should do one thing and only one thing. This function validates that the rate passed is in a valid range and then puts it in the field.
I removed the duplicate code that was scraping the INPUT twice. Just do it once, save it in a variable, and reuse that variable. In this case, there's no need to scrape it twice.
and as d0x said, you shouldn't convert the s1 string to a float and then back to string when you sendKeys() ... just send the s1 string. Translating it back doesn't help readability, it just means you wrote more code that someone after you will need to understand. Favor clean code... it's always more readable.
public static String enterRate(String s1)
{
f = Float.parseFloat(s1);
WebElement input = webDriver.findElement(By.xpath(".//*[#id='p_InvestmentSelection_4113']/div/div/div[5]/div/ul/li/div[3]/div[2]/label/div[1]/input"));
if ((f < 0) || (f > 6))
{
error = "Value must be between 0.00% and 6.00%";
}
else
{
input.sendKeys(s1);
}
return error;
}
Can you try passing s1 instead of f. Because the method takes a string, not a float.
Your method should look like this:
String selector = "expression";
webDriver.findElement(By.xpath(selector)).sendKeys(f);
And please use better variable names like userInput instead of s1 or userInputAsFloat instead of f or investmentInputVisible instead of bool etc.

java singleton boolean expression to return message instead of true or false

How can we get the boolean expression of a basic singleton with hashsets to return a message in lieu of the original 'true' or 'false'?
public boolean bookLane(String lane) {
return runLane.remove(lane);
}
I want to only replace the true or false return statements with a message.
To help clarify this question, something like below (i know it doesn't work) is the direction I am wanting to go...
public boolean bookLane(String lane) {
if (true)
{
message = "Lane is available. Adding runner...";
//instead of true
}
else
{
message = "Lane unavailable. Please choose another";
//instead of false
}
return runLane.remove(lane);
}
I just tried messing with the code and found that it only returns false now.
public boolean bookLane(String lane) {
String message1 = "Lane Available. Adding runner...";
String message2 = "Lane is Unavailable.";
if (runLane.remove(lane))
{
System.out.println(message1);
}
else
{
System.out.println(message2);
}
return runLane.remove(lane);//
}
Any ideas on fixing it? Not gonna lie, my experience with Java is mainly trial and error with a little help from more experienced programmers. I think this method could work if someone could let me know what I am missing as far as how boolean methods work with more than just the one return type. I am trying to target the return value for displaying the appropriate message with the returned boolean. Is this route even possible? Am I missing some logic in how boolean methods work or something? Please understand my frustration and my need for yalls help. thanks for the guidance given...
In these cases it might be useful to define a new data structure, since you want to retrieve two pieces of information from the same method. Consider the following:
class BookLaneResult {
boolean success;
String message;
// add constructors / getters / other stuff you need
}
Then your code becomes this:
public BookLaneResult bookLane(String lane) {
// some logic to determine if lane is available or not
boolean laneAvaiable = ...;
return new BookLaneResult(laneAvailable, laneAvailable ? "Lane available" : "Lane unavailable");
}
If the BookLaneResult is to be used only in that case with only those messages, then you can just use a boolean parameter constructor and set the message based on the argument internally. However, to make the new data structure more flexible you can name it OperationResult and use it whenever you perform some kind of operation and expect to retrieve a boolean flag representing the operation success or failure and the message stating what happened.
Here is what I used for a boolean operation trying to figure out if a character is a letter - if it is a letter, true, false if no.
Code
boolean isLetter = Character.isLetter(ch);
if (isLetter == true) {
Boolean.toString(isLetter);
System.out.println(" This is a letter."); }
else {
Boolean.toString(isLetter);
System.out.println(" This is not a letter."); }
Worked for me - might be able to apply to other boolean operations.
Output
Input data: 123456abcdef
1 2 This is not a letter
2 3 This is not a letter
3 4 This is not a letter
4 5 This is not a letter
5 6 This is not a letter
6 7 This is not a letter
a b This is a letter
b c This is a letter
c d This is a letter
d e This is a letter
e f This is a letter
f g This is a letter
I realize this is years late, but including this for those who pop up on this thread from a Google search.

Java Palindrome Program (am I on track)?

I have only 6 months of Java experience (and I'm also new here) so please bear with me if things don't look entirely right in my code. Please note that it's still a work in progress. I'm trying to write a program that takes in strings and prints only the ones that are palindromes.
I'm supposed to:
- create a method named isPalindrome, which has a String parameter and
- returns a Boolean based on whether the string is a palindrome or not. Then
- modify the main method to use isPalindrome to print only the palindromes.
For example, if I type: "madam James apple mom timer", it should print "madam" and "mom".
This is basically the program I am trying to write:
Ex: Let's use the word "madam". The program will check if the first and last letters match ("madam"). If that is true, then it'll check the next letters, this time "a" and "a" ("madam). And so on and so forth.
This is the Java code I have so far:
public class Palindrome
{
private String theWord; //Error: The value of the field Palindrome.theWord is not used
public boolean isPalindrome( String theWord ) {
int firstPointer = 0;
int secondPointer = theWord.length() - 1;
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved or is not a field
return true;
}
return false;
}
}
public static void main( String[] theWord ) {
Palindrome = new Palindrome( ); //Error: Palindrome cannot be resolved to a variable
for ( int i = 0; i < theWord.length; i++ ) {
while (firstPointer < secondPointer) { //Error: "firstPointer" cannot be resolved to a variable. "secondPointer" cannot be resolved to a variable
if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved to a variable or is not a field. Cannot invoke length() on the array type String[]
firstPointer++; //Error: "firstPointer" cannot be resolved to a variable
secondPointer++; //Error: "secondPointer" cannot be resolved to a variable
}
System.out.println(theWord);
}
}
}
}
Any bit of help knowing where I've gone wrong would be greatly appreciated. Please don't just give me the right code. I would like to figure this out. Thank you very much.
**EDIT: I've included the errors as comments in the code now. I'm using Eclipse by the way.
-->**EDIT 2: Okay guys. I've read most of your answers and have been able to correct most of my code so far (Thank you all so much so far). The only part I'm still having an issue with right now is this part:
if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) ) {
leftPointer++;
rightPointer--;
I'm now getting a "Cannot invoke charAt(int) on the array type String[]"
and "Cannot invoke length() on the array type String[]".
Those are the only two errors remaining, then I'll test the code out. I've been trying to resolve them for a while now but I'm still not entirely sure what those errors mean.
Eclipse is suggesting that I change theWord.charAt(i) to theWord.length which is not what I want. It is also suggesting I remove "( )" from length but I don't think that's right either.
Looking at your isPalindrome method :
if ( theWord.charAt(0) == theWord.charAt (theWord.length() - 1)
here you always compare the first character to the last character. In each iteration you should compare a different pair of characters, until you find a pair that doesn't match, or reach the middle of the word.
You should use the i variable of your loop :
if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1)
And the return value should be the exact opposite. If you find a pair of characters that don't match, you return false. Only if the loop ends without returning false, you return true.
Okay, let's break everything down into little sizable chunks.
Input a string
Parse the string, check if it is a palindrome.
Print out the words in the string which were palindromes.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scan.nextLine(); // 1.
String[] words = sentence.split(" ");
for (String word : words) { // 3.
if (isPalindrome(word)) {
System.out.println(word);
}
}
}
/**
* Check if the string is a palindrome.
* #param string
* #return True if string is palindrome.
*/
public static boolean isPalindrome(String string) { // 2.
for (int i = 0; i < string.length() / 2; i++) {
if (string.charAt(i) != string.charAt(string.length() - i - 1)) {
return false;
}
}
return true;
}}
Some explanation
The method/function isPalindrome is static because we are calling it from a static context, that is the main function. If you want to use it non-statically you would place it in a class and create a object from that class. The rest should be understandable. :-)
A better isPalindrome method
The shortest way is probably just following the definition:
If you reverse the string, and it's still the same, then it's a palindrome:
public static boolean isPalindrome(String input)
{
String reverse = new StringBuilder(input).reverse().toString();
return input.equalsIgnoreCase(reverse);
}
But if there is an educational goal (?), and iterators should be used for some reason then, imho it makes more sense to iterate from the outside towards the inside of the string.
public static boolean isPalindrome(String input)
{
int length = input.length();
for (int i = 0; i < length/2 ; i++)
{
if (input.charAt(i) != (input.charAt(length-1-i))) return false;
}
return true;
}
Phrase parsing
In your example you used the input of the main String[] parameter. Here is just some information in case you wanted to split it to words manually.
Equivalent to what you got now:
String[] words = phrase.split("\\s+");
for (String word : words)
{
// do stuff
}
The split method uses a delimiter to split a String into a String[]. The delimiter \\s is a regex that represents all kinds of whitespace (not only spaces, but also tabs, new-line characters, etc ...).
But it's not perfect (and neither is your way), there can still be commas, dots and other marks in the phrase. You could filter these characters in an iteration, using the Character.isLetterOrDigit method. Alternatively, you could just perform a replace(...) to remove comma's, points and other marks. Or you could use more complex regular expressions as well.
About your code
The first error message : "The value of the field is not used".
The error message is caused by the global private field theWord, because it is never used. It's not used because you also have a parameter with the same name inside the method isPalindrom(String theWord). Whenever you reference theWord inside that method, it will always give advantage to method arguments before considering global variables.
It looks like you are stuck here with a design contradiction.
What exactly is the class Palindrome ? There are 2 options:
Is it supposed to be a toolbox like the Math class ? like boolean value = Palindrome.isPalindrome("madam");?
Or is it supposed to be an Object that you instantiate using a constructor ? like boolean value = new Palindrome("madam").isPalindrome();
Option 1: a toolbox:
public class Palindrome
{
// removed the private field theWord
// make this method static !!
public static boolean isPalindrome( String theWord ) {
...
}
public static void main( String[] theWord ) {
// remove the Palindrome object
// inside the loop check use the static method
// which does not require an object.
if ( Palindrome.isPalindrome(word))
{
}
}
}
Option 2: an object
public class Palindrome
{
// keep the private field theWord
private String theWord;
public Palindrome(String theWord)
{
// set the value of the argument to the private field
this.theWord = theWord;
}
// don't make this method static
// also you don't need the parameter any more.
// it will now use the global field theWord instead of a parameter.
public boolean isPalindrome() {
...
}
public static void main( String[] theWord ) {
// inside the loop check use an object
Palindrome palindrome = new Palindrome(word);
if ( palindrome.isPalindrome())
{
}
}
As for the errors about the firstPointer and secondPointer. You need to define and initialize those variables. I.e. put int firstPointer = 0; before the loop.
In the loop check it out this way:
boolean isPalin = true;
for ( int i = 0; i < theWord.length( )/2; i++ ) { // loop goes till half since no need to check after that
if ( !(theWord.charAt(i) == theWord.charAt (theWord.length() - 1 - i)) ) { // will check each letter with each end letter
isPalin = false;
break;
}
}
return isPalin;
Another things to add -
1 -firstPointer secondPointer are local variables to isPalindrome
2 - When u have decalared theWord as global variable there doent seems a need to pass it. You can use it within the same class.
3 - theWord in main(String[] theWord) would require you to provide input as arguments, it better you go for console input at runtime.
4 - In main you should split each word and pass it to isPalindrome. In your code you are not calling isPalindrome to check anywhere.

error: '.class' expected [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
Hi friends while compiling the below error is coming
error: '.class' expected
I'm not able to find what is the error. I checked in many websites but not able to find why this error is coming. Plz Help
Thanks in advance.
import java.io.*;
class Test
{
boolean isGoodEmployee(boolean ismarried,int noofchild,String middlename,String childnames[])
{
boolean child,letter,last,child;
if (noofchild <= 2)
child=true;
boolean firstletter = middlename.startsWith("k");
boolean lastletter = middlename.endssWith("e");
if (firstletter && (!lastletter))
letter = true;
int lastnameletterscount = lastname.length();
if (lastnameletterscount > 4)
last = true;
String name = raju;
for (int i=0; i < noofchild; i++)
if(name.equalsIgnoreCase(childnames[i]))
{
child = true;
break;
}
}
}
class GoodEmployee
{
public static void main(String args[]) throws IOException
{
String firstname, middlename, lastname;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the first name of employee");
firstname = br.readLine();
System.out.println("enter the middle name of employee");
middlename = br.readLine();
System.out.println("enter the last name of employee");
lastname = br.readLine();
//System.out.println("full name of employee is:"+first+middle+last);
System.out.println("enter employee is married or not");
boolean ismarried = Boolean.parseBoolean(br.readLine());
if (ismarried)
System.out.println("enter number of childrens");
int noofchild = Integer.parseInt(br.readLine());
String childnames[] = new String[noofchild];
System.out.println("enter children names");
for (int i=0; i < noofchild; i++)
childnames[i] = br.readLine();
Test t = new Test();
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
}
}
I'm using "javac GoodEmployee.java" to compile the program
You have a mis-matching method call in isGoodEmployee.
The childnames argument is defined as an array, so you can simply pass in the argument, replace:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
with
t.isGoodEmployee(ismarried,noofchild,middlename,childnames);
Aside from that, do not ignore other compilers errors such as
middlename.endssWith("e");
^---------extra 's'
Familiarize yourself with the javadocs.
there's plenty wrong with this code:
you've declared boolean child twice in isGoodEmployee() (1st line)
endssWith should be endsWith()
and so on, but nont of them are the issue you stated. what command line are you using for compiling this class?
#Reimeus has nailed it.
The strange compilation error can be explained as follows. In this line:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
the childnames[] phrase is supposed to be a Java expression. But in fact, the syntax most closely resembles a type ... in fact an array of some (non-existent) class called childnames. The Java compiler's syntax error recovery code has decided that if it inserts .class after the typename (i.e. childnames[].class) that will give a syntactically valid expression.
Of course, the correction that the compiler is suggesting is nonsensical ... not least because there won't be a class or interface named childnames in your application.
The moral of the story is that unusual syntax errors sometimes cause a compiler to produce peculiar error messages that only make sense if you can figure out how the parser would have parsed the erroneous input.
Make the class with the main method public if you are using an IDE.
In case you are trying to run it using command window I don't think a '.class' file is required for compiling rather it would be required for execution. So after you have a .class file by entering javac GoodEmployee and you have no errors enter java GoodEmployee which will execute the .class file you have.

Categories

Resources