jeudi 15 août 2019

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

}

Aucun commentaire:

Enregistrer un commentaire