how do you initialize a variable that is declared? - java

if (eyeColor == green)
{
System.out.println ("If your eyes are green I recommend buying .... ");
....
}
error says
variable green might not have been initialized
I can't display my whole code since it is for school, but I am just wondering how can I initialized it if the eyeColor from the user input (using scanner) is green?

Not sure what is the type of green but this is how you declare method local variables:
Object green = null;
or
Object green = SOME_DEFAULT_VALUE_BETTER_THAN_NULL;

Initialise eyeColor before you compare it.
If it is a string, simply initialise it as an empty string:
String eyeColor;
eyeColor = "";
Before you perform any checks to see what eyeColor has been specified, you may also want to check to make sure that is is NOT still ""..

Assuming that your variable eyeColor is the input from the user. You could use the following
if("green".equals(eyeColor))
Since green is a string, and it will never change (it is always green), you can just use the string. It is also worth noting that in Java, you need to use .equals() when comparing string values, not '=='.
I would also suggest using .toLowerCase(), so that the comparison is no longer case sensitive. An example check is shown in the code below:
public static void main(String args[]) throws IOException {
String eyeColor = "Green";
if("green".equals(eyeColor.toLowerCase())){
System.out.println ("If your eyes are green I recommend buying .... ");
}
}

Related

What's a better or more standard way to perform this function?

I am a java beginner, and in this particular problem I practiced making a program that converts any given string to lowercase string. Is there a a better way to achieve this goal in java (in terms of design)?
Also, how does the "else" (after "else if") catches or waits for me to make an input. Somehow that part does not make sense to me, even though I achieved what I wanted. How is the value of "ans" from input transferred to the entire loop and used until the loop is closed?
After many attempts and failures, I used a separate method for the conversion part. My second question is a bit too complicated to be researched.
import static java.lang.System.out;
import java.util.Scanner;
public class MyClass {
public static Scanner s = new Scanner(System.in);
public static String ans;
public static void main(String args[]) {
Conversion();
do {
ans = new String(s.nextLine());
if (ans.equalsIgnoreCase("Y")) {
Conversion();
} else if (ans.equalsIgnoreCase("N")) {
out.println("Thank you for using this program!");
break;
} else {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
} while (ans != "N");
}//END MAIN
public static void Conversion() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
out.println("Your new string is: " + str.toLowerCase());
out.println("Would you like to convert another string? (Y/N)");
}
}
I notice a few issues; Conversion looks like a class-name (Java naming convention would be conversion) and ans != "N" is using == instead of .equals - and wouldn't ignore case (!ans.equalsIgnoreCase("N")). Globals (e.g. static) are bad (pass the Scanner to the methods that need it), and the static import just makes the code more difficult to reason about (in my opinion). Your current loop doesn't really follow a conventional form, I would extract the prompt and loop for "another" conversion to a new method and if you must print a thank you I'd do so after the "main loop". Something like,
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
do {
conversion(sc);
} while (another(sc));
System.out.println("Thank you for using this program!");
}
public static void conversion(Scanner s) {
System.out.println("Please enter string to be converted to lowercase: ");
System.out.printf("Your new string is: %s%n", s.nextLine().toLowerCase());
}
public static boolean another(Scanner s) {
while (true) {
System.out.println("Would you like to convert another string? (Y/N)");
String ans = s.nextLine();
if (ans.equalsIgnoreCase("Y")) {
return true;
} else if (ans.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Invalid entry!");
System.out.println("(Please type 'Y' for yes, or 'N' for no.)");
}
}
Answering your first question:
There are many design patterns and practices so many people can argue what I would recommend you to do. It's basically the same for all programming languages. Let's take your function "Conversion". The name itself says that you use it to convert stuff. Not to display, not to prompt - to convert. In this case, the only actual thing it should do is to convert upperCase to lowercase. In fact, you might want to specify what type of conversion it has in the name of the function (convertToLowerCase?). In fact, in Java, we use lowerCamelCase for all function names and UpperCamelCase for classes.
If you accept my previous suggestion, you could break the Conversion function into multiple ones like promptUserForInput, WrongInputHandler and so forth.
If I understood your second question correctly, you wonder about the way the code executed and how the variable ans is transferred further into the loop. Let's take a look at your code and what variables do:
You initialize your variable in the class MyClass by making it accessible to all methods in the class;
You prompt the user for the input to assign to this variable inside the do..while loop with this line ans = new String(s.nextLine()); which saves the value of the variable and, again, which can be accessed inside the whole class so its value is changed.
It goes into the if..else if...else statement. The way it works, it goes line by line - if the first if-statement fails, it goes on until it finds a truthy statement and it doesn't go any further. In your case, if the ans is not equal to either y/Y/ it will go to else if statement and if it's not n/N, it will go to else (so basically whatever except y/Y/n/N) and will be executed. After that, it jumps into the while (ans!= "N"); line where it compares your class-member variable ans and if it's not equal to "N" it starts over the loop right after the do{ part until you type in the "N".
I hope that makes sense. Whenever the program is asking you for input, it does not execute code further but is stuck until you provide any input. The value from input itself isn't passed throughout the loop and the program. The reason why you can use it because you created a higher-scope variable ans where you saved the result of your input.
IMPORTANT: if you've declared the ans inside the do..while loop, you would've not been able to have accessed it in the while (ans...) because it will 'die' right before the curly brace between do { ...here} while(). If you want to learn more about the scope and variables in general, you can read this article.
Here is my code example:
public static void main(String args[]) {
//declare before entering the loop to have higher scope
String ans = "y";
do {
//we get the given string to convert from the user
String str = promptForString();
//we convert the string
str = converseStringToLowerCase(str);
//display the string (could use another function for that: easier to debug and locate problems and in bigger projects)
out.println("Your new string is: " + str);
//prompt user for respond to continue or not
ans = promptForContinue();
handleResponse(ans);
} while (!ans.equals("n"));
}//END MAIN
//prompts user for an input string
public static String promptForString() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
return str;
}
//converts any given string to lower case
public static String converseStringToLowerCase(String str) {
return str.toLowerCase();
}
//is used to prompt user for reply
public static String promptForContinue() {
out.println("Would you like to convert another string? (Y/N)");
String str = new String(s.nextLine());
//is good to make if...else statements easier - it will always be lower case (or upper if you prefer)
return str.toLowerCase();
}
//easier to locate other response scenarios
public static void handleResponse(String response) {
if (response.equals("n")) {
out.println("Thank you for using this program!");
//it's not a very good practice to innaturally break loops. Use input for that in while(..) statement
// break;
} else if (!response.equals("y")) {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
}

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 Scanner: Continuous loop

When I input any valid option (A,B,C) the if statement thinks that option is anything but A, B, or C, and will lead into a continuous loop.
package other;
import java.util.Scanner;
public class Menu implements InterfaceMenu{
private String option;
public void greeting(){
System.out.println("This program will use the Pythagorean Theorem");
System.out.println("to calculate a missing side.\n");
System.out.println("Choose an option!\n");
System.out.println("Choose Option A for missing side c");
System.out.println("Choose Option B for missing side b");
System.out.println("Choose Option C for missing side a\n");
}
public String optionGet(){
System.out.print("Choose an option: ");
Scanner ad = new Scanner(System.in);
option=ad.next().toUpperCase();
if( (option=="A") || (option=="B") || (option=="C") ){
ad.close();
}
else{
optionGet();
}
return option;
}
}
Aside from using the wrong method to compare strings, there is another serious problem: optionGet() opens a new Scanner on system.in. If the input contains an option that is not A, B, or C, then optionGet() calls itself recursively. The recursive call does another
Scanner ad = new Scanner(System.in);
while the first one is still open. There is no telling just what that will do, but it is likely to cause problems. Do not do that. Don't use recursion. It's inappropriate here. Instead, put the code that checks for options in a loop, and make sure new Scanner is outside the loop.
use option.equalsIgnoreCase("A") instead of ==. because == compares the reference variables and equals compars the content .
In Java strings cannot be compared using the == identifier in the same way as you would for integers. Instead you can use String.equals().
For what you have written however it may be best to compare characters however that will require changing the returned variable type within optionGet() to public char optionGet(). Doing this however will also require you to change the type of option to char. Changing the type to char will allow you to compare characters using ==.
Also be sure to define Scanner ad outside of optionGet() as your current code is redefining it for every reiteration.
Your call as to what you think is easier.
Use the the String.equals() method. Not the == comparator. Whereas .equals() checks for equality between strings, == checks if their references are the same, which isn't what you want to do.

Beginner Java strings [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
So, I have a question regarding the testing operators and strings. I'm trying to write a program that will take in user input of either "boy" or "girl". When the user inputs "boy", the output should be "You are a boy." When the user inputs "girl", the output should be "You are a girl."
However, when I compile and run the program, no matter what I input, the output is always "You are a girl."
Is this because the strings have no actual value like integers and therefore, testing operators cannot be used to compare them?
Also, is there anything like the assert function from python in java?
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
if (text == "boy"){
System.out.println("You are a boy.");
}
else{
System.out.println("You are a girl.");
}
}
}
Thanks a lot~
Use
text.equals("boy")
instead of
if (text == "boy")
The reason is, In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
But the better option is to use equalsIgnoreCase, the reason is that user may enter boy or BOY or Boy or any other combination. equalsIgnoreCase method just ignores the case and compares two strings.
text.equalsIgnoreCase("boy")
Side note. Input other than Boy will get you to print Girl. Put one more extra if condition. Also before going for comparision, being on safer side trim the string for blank spaces.
Use
text.equals("boy")
or
text.equalIgnoreCase("boy")
if its not case sensitive.
instead of
if (text == "boy")
Your coade will be something like this
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
text = text.trim();
if (text.equalIgnoreCase("Boy")){
System.out.println("You are a boy.");
}
else if(text.equalIgnoreCase("Girl")){
System.out.println("You are a girl.");
} else {
System.out.println("Invalid Gender");
}
}
}
use text.equalsIgnoreCase("boy")
if you think about case also it will check content of string is same.
== is used to check for object equality.
text.equals("boy") is ok if you not consider about case.
Please use equals method for string like : if (text.equals("boy")){
== is not for string contents equality check in java
== tests if object identity is the same. When you have two string objects containing the same value this object identity won't be equal. Use the equals function to test for logical equivalence.
Your if else is wrong. Use only if here. Otherwise,
If I entered "some text", the output will be "You are a girl"
Like this
if (text.equalsIgnoreCase("boy")) {
System.out.println("You are a boy.");
}
else if (text.equalsIgnoreCase("girl")) {
System.out.println("You are a girl.");
} else {
System.out.println("You are neither a boy nor a girl");
}
It would be best to use the .equals method instead of == boy
For your other question regarding assert:
Java has an assert function. This is the sample code.
assert(x <= 50): "Not Accepted";
This code checks if integer x is greater than 50. You will see the output at the console.

Java, how to compare Strings with String Arrays

I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}

Categories

Resources