Get a character from its Unicode index

I’ve been working my way through these Java exercises at w3resource.com, and at one point I wanted to be able to get a particular Unicode character from its index. For example, I wanted to turn the integer 65 (or 41 in hexadecimal) into the unicode character U+0041, or a capital letter “A”. This was for a program which would convert a given decimal number to its hexadecimal equivalent:

import java.util.Scanner;

public class decimalToHex {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);

    System.out.print("Insert a positive integer: ");
    int num = in.nextInt();
    String hex = "";
    int uni = 0;

    while(num != 0){
      uni = num % 16;
      if(uni > 9){ hex = Character.toString((char)(uni+55)) + hex; }
      else       { hex = Character.toString((char)(uni+48)) + hex; }
      num /= 16;
    }

    System.out.println(hex);

    return;
  }
}

As you can see in the code above, the way I accomplished this was to typecast the integer values (uni+55 or uni+48) to a char, then convert that char to a String. Another way to do this (as was done in the example solution) is to define a 16-character or a 16-String array of 0-9 and A-F, and just add the appropriate character to “hex” with:

String[] myarray = { "0", "1", "2" ... "D", "E", "F" }
...
hex = myarray[uni] + hex;
Advertisements

Java Potpourri I

I took a trip to Barnes & Noble today and found a really neat book, “Sams Teach Yourself Java in 24 Hours“. After working through the first few chapters, I found a few interesting odds and ends. Specifically (1) how to work with Strings, (2) switch statements, and (3) working with date and time. Strings are quite easy to work with in Java, and no imports are necessary:


public class Strings {

  public static void main(String args[]){

    String test = "test";
    String word = "word";

    System.out.println(test.equals(word));
    System.out.println(test + " has " + test.length() + " letters.");
    System.out.println(word.toUpperCase());

    String uppercase = "UPPERCASE";

    System.out.println(uppercase.toLowerCase());
    System.out.println("Does " + uppercase + " contain \"CASE\"?");
    System.out.println(uppercase.contains("CASE"));

    System.out.println("Okay, where is it?");
    System.out.println(uppercase.indexOf("CASE"));

    System.out.println("Does " + test + " contain \"CASE\"?");
    System.out.println(test.contains("CASE"));

  }

}

Several methods are used above, including equals(), which returns true if two Strings are the same, character-by-character; length(), which returns the length of a given String; toUpperCase() and toLowerCase() which convert all of the characters in a string to uppercase and lowercase, respectively; contains() which returns true if a String contains a given substring; and indexOf() which first checks if a String contains a given substring and then returns the index of the beginning of that substring if it is contained within the String of interest.

Additional String methods are described in the Oracle Java tutorials, including charAt(), which retrieves the character of a particular String at the desired index; concat(), which concatenates two Strings (though this can more easily be achieved with a +=); and format(), which allows a C-style construction of Strings from variables of different data types:

public class Format {

  public static void main(String args[]){

    int myInt = 4;
    double myDouble = 3.5;
    String myString = "myString";

    String myFormat = "";

    myFormat = String.format("myInt: %d\nmyDouble: %f\nmyString: %s",
      myInt, myDouble, myString);

    System.out.println(myFormat);

  }

}

Another small difference I found today between Java and C++ is that Java allows underscores “_” in integer values to help break up the powers of ten. For instance:


public class Underscores {

  public static void main(String args[]){

    int a = 17_000;
    int b = 17000;

    System.out.println("a = " + a);
    System.out.println("b = " + b);

  }

}

will print

15:28 |aww@airy Underscores| javac Underscores.java 

15:28 |aww@airy Underscores| java Underscores
a = 17000
b = 17000

while in C++, the following code returns an error

#include <iostream>
using namespace std;

int main(){

  cout << "This is a test." << endl;

  int a = 17_000;
  int b = 17000;

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  return 0;

}

Underscores are also allowed in Perl, but not, apparently, in C++. Another interesting thing I came across while reading this book is that, in Java, switch statements can take Strings as arguments:

public class Switch {

  public static void main(String args[]){

    String controller = "greeting";

    switch(controller){
      case "greeting":
        System.out.println("Hello!");
        break;
      case "farewell":
        System.out.println("Bye!");
        break;
      case "Hawaiian":
        System.out.println("Aloha!");
        break;
    }

  }

}

I thought I remembered that only integers could be used in switch statements in C++, so I wrote a bit of code to check:

#include <iostream>

using namespace std;

int main(){

  char a = 'a';
  char b = 'b';

  char controller = a;

  switch(controller){
    case 'a':
      cout << "controller = " << a << endl;
    break;
    case 'b':
      cout << "controller = " << b << endl;
    break;
  }

  return 0;

}

The C++ code runs fine, so I was mis-remembering. Finally, the book gives an example for working with dates and times in Java. Here’s my slightly edited version from what the book gives:

import java.time.*;
import java.time.temporal.*;

class Clock {

  public static void main(String[] args){

    // get current time and date
    LocalDateTime now = LocalDateTime.now();

    int hour   = now.get(ChronoField.HOUR_OF_DAY);
    int minute = now.get(ChronoField.MINUTE_OF_HOUR);
    int month  = now.get(ChronoField.MONTH_OF_YEAR);
    int day    = now.get(ChronoField.DAY_OF_MONTH);
    int year   = now.get(ChronoField.YEAR);

    // display greeting
    if(hour < 12){
      System.out.println("Good morning!");
    } else if(hour < 17){       System.out.println("Good afternoon!");     } else {       System.out.println("Good evening!");     }     // begin time message by showing the minutes     System.out.print("It's");     if(minute != 0){       System.out.print(" " + minute + " ");       System.out.print( (minute != 1) ? "minutes" : "minute");       System.out.print(" past");     }     // display the hour     System.out.print(" ");     System.out.print((hour > 12) ? (hour - 12) : hour);
    System.out.print((hour > 11) ? " pm" : " am");
    System.out.print(" on ");

    // display the name of the month
    switch(month){
      case 1:
        System.out.print("January");
        break;
      case 2:
        System.out.print("February");
        break;
      case 3:
        System.out.print("March");
        break;
      case 4:
        System.out.print("April");
        break;
      case 5:
        System.out.print("May");
        break;
      case 6:
        System.out.print("June");
        break;
      case 7:
        System.out.print("July");
        break;
      case 8:
        System.out.print("August");
        break;
      case 9:
        System.out.print("September");
        break;
      case 10:
        System.out.print("October");
        break;
      case 11:
        System.out.print("November");
        break;
      case 12:
        System.out.print("December");
        break;
    }

    // display the date and year
    System.out.print(" " + day + ", " + year + ".");

  }

}

Once the initial hurdle of understanding the syntax is overcome (now.get(ChronoField…)), dates and times seem to be pretty easy to work with in Java.

Reversing a number in Java

I have a lot of experience with C++. So while learning about if-else statements and loops is interesting, it’s essentially the same between C++ and Java. That being said, I think the best way to learn a programming language is to just write code in that language. So I’ve looked around for examples online and I found a few decent tutorial sites. The following code is taken from the second last site linked in the previous sentence, and the purpose of the code is to reverse a number (so 34 would become 43, 57 would become 75, etc.).

I don’t want to just copy the code from this example, but I did need to look up how to take user input. It seems like the easiest way is with java.util.Scanner, which can read in single variables or lines of text from the command line. Also, I wanted to look up how to construct Strings, because I wanted to avoid a case where “90” might be reversed to “9” instead of “09”. I want the output to be a String, not an integer.

import java.util.Scanner;

public class ReverseNumber {

  public static String reverseIt(int oldInt){

    String newInt = "";
    newInt += oldInt%10;
    newInt += (oldInt - (oldInt%10))/10;
    return newInt;

  }

  public static void main(String args[]){

    Scanner userInt = new Scanner(System.in);

    System.out.println("Enter any number between 10 and 99: ");
    int myInt = userInt.nextInt();

    System.out.println("You entered: " + myInt);
    System.out.println("Reversed, that is: " + reverseIt(myInt));

  }

}

…it works! Strings are pretty easy to work with in Java, too. And since they’re a basic data type, no extra packages need to be included. This is in stark contrast to C++, where strings are more complex and a bit more difficult to work with. Strings can also be constructed with a StringBuilder() object or using String.format() for a more C-style look.