JavaScript Sample: Data Exchange

JAVA TASK:

Create Java application that shows the following each time the Enter key is pressed:

    1. an invitation for user to input “num” message, which would result in NUM LOCK key state being displayed (using green text on blue background);
    2. an invitation for user to input “caps” message, which would result in CAPS LOCK key state being displayed (using red text on yellow background);
    3. an invitation for user to input “quit” message, which would result in quitting the application;
    4. any other user message should be marked as unrecognized.

SOLUTION:

In this sample we are going to inspect some of the more advanced functionality when it comes to dealing to data exchange between the user and Java application through the console window. As you probably already know, this means that all the information comes in the form of text, with the user being expected either to make/confirm choices, or input text data.

Since the program is meant to work cyclically each time Enter is pressed (that is, each time the user inputs his message), we will need to use a looping statement. Let us also provide the user with option to end it if he inputs the “quit” keyword. The basic looped code would look as follows:

package testproject2;

//importing Scanner class
import java.util.Scanner;  

public class TestProject2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //a strings type variable used to store text
        String textvar;
        textvar = "";
        //creating new scanner object which takes InputStream as parameter
        Scanner in = new Scanner(System.in);
            do
            {
                //we have used “\” symbols as a way to display the brackets as part of text
                System.out.println("Input some text. Inputting \"quit\" exits the program,");
                textvar = in.nextLine();
            }
            while (!"quit".equals(textvar)); 	
            //loop will repeat until textvar reaches the necessary value
    }  
}

Such application will keep on prompting the user to enter a message until he inputs “quit”, after which the application will stop running. Next, let’s add the display of NUM LOCK and CAPS LOCK states into the loop. The most basic Java package for displaying these is awt, the value is taken only once, but it is sufficient for our purposes:

package testproject2;

//importing Scanner class
import java.util.Scanner;  

//importing packages used for detecting key events
import java.awt.Toolkit;
import java.awt.event.KeyEvent;

public class TestProject2 {

    /**
     * @param args the command line arguments
     */
      
    public static void main(String[] args) {
        //a strings type variable used to store text
        String textvar = "";
        //creating new scanner object which takes InputStream as parameter
        Scanner in = new Scanner(System.in);
        //creating new toolkit
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        //creating NumLock and CapsLock flags
        boolean NumLockOn; 
        boolean CapsLockOn; 
        do
        {    
            //we have used “\” symbols as a way to display the brackets as part of text
            System.out.println("Input \"num\" for NumLock state display");
            System.out.println("Input \"caps\" for CapsLock state display");
            System.out.println("Input \"quit\" for exiting the application");
            System.out.println("Input some other message to place it as new titlebar");           

            textvar = in.nextLine();
            if("num".equals(textvar))
            {
                NumLockOn = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
                //this can be done with if-else statement...
                if (NumLockOn)
                {
                    System.out.println("NUM LOCK was on.");
                }
                else
                {
                    System.out.println("NUM LOCK was off.");
                }
            }
            else if("caps".equals(textvar))
            {     
                CapsLockOn = toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                //...or alternatively with conditional operator (?:)
                System.out.println("CAPS LOCK was " + (CapsLockOn ? "on" : "off") +".");
            }     
            else if(!"quit".equals(textvar))
            {
                System.out.println("Unrecognized message");
            }
        }
        while (!"quit".equals(textvar)); 	
        //loop will repeat until textvar reaches the necessary value
    }  
}

Now we should upgrade the code with text/background color alteration, as well as ability to update the titlebar on each loop. Coloring the console output in Java may be a bit more tricky than in other object-oriented languages, and the simplest method would be to use ANSI escape codes.

From the following article:
https://en.wikipedia.org/wiki/ANSI_escape_code
we can learn that the following codes would be of interest to us:

00: Reset back to defaults
30-37: Set text color (foreground), equals to 30+N
39: Default text color (foreground)
40-47: Set background color, equals to 40+N
49: Default background color

Where N values of 0,1,2,3,4,5,6,7 correspond to black, red, green, yellow, blue, magenta, cyan, and white color respectively.

In other words we will use the following codes:
green text: 32
blue background: 44
red text: 31
yellow background: 43

We will also need to reset text and background colors back to the default values each time we no longer need to use them. This results in the following code:

package testproject2;

//importing Scanner class
import java.util.Scanner;  

//importing packages used for detecting key events
import java.awt.Toolkit;
import java.awt.event.KeyEvent;

//importing ANSI packages for text color
import java.awt.Color;

public class TestProject2 {

    /**
     * @param args the command line arguments
     */
      
    public static void main(String[] args) {
        //a strings type variable used to store text
        String textvar = "";
        //creating new scanner object which takes InputStream as parameter
        Scanner in = new Scanner(System.in);
        //creating new toolkit
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        //creating NumLock and CapsLock flags
        boolean NumLockOn; 
        boolean CapsLockOn; 
        do
        {              
            //we have used “\” symbols as a way to display the brackets as part of text
            System.out.println("Input \"num\" for NumLock state display");
            System.out.println("Input \"caps\" for CapsLock state display");
            System.out.println("Input \"quit\" for exiting the application");
            System.out.println("Input some other message to place it as new titlebar");           

            textvar = in.nextLine();
            if("num".equals(textvar))
            {
                NumLockOn = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
                //this can be done with if-else statement...
                if (NumLockOn)
                {
                    System.out.println((char)27+"[32;44m"+"NUM LOCK was on."+(char)27+"[00;00m");
                }
                else
                {
                    System.out.println((char)27+"[32;44m"+"NUM LOCK was off."+(char)27+"[00;00m");
                }
            }
            else if("caps".equals(textvar))
            {     
                CapsLockOn = toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                //...or alternatively with conditional operator (?:)
                
                System.out.println((char)27+"[31;43m"+"CAPS LOCK was " + (CapsLockOn ? "on" : "off") +"."+(char)27+"[00;00m");
            }     
            else if(!"quit".equals(textvar))
            {
                System.out.println("Unrecognized message");
            }
        }
        while (!"quit".equals(textvar)); 	
        //loop will repeat until textvar reaches the necessary value
    }  
}

The result can be tested in the NetBeans environment, since it will display color changes even in case ANSI codes are not supported by your default Windows console window.

JavaScript sample you’ve recently looked through was completed by one of Assignment.EssayShark experts as well as other Javascript code examples. Contact us if you need fast and qualified help in technical disciplines. We work 24/7 to provide you with academic help of any difficulty level. Timely delivery, simple explanations and constant support are guaranteed.

Leave a Reply

Your email address will not be published. Required fields are marked *

Customer testimonials

Submit your instructions to the experts without charge.