How do I write java code that will only accept capital A or B input from the user?

Code:
import java.util.Scanner;
public class ReadChar {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner( System.in );
 
    String letter = "";
    while(true) {
      System.out.print("Please enter a letter: ");
      letter = sc.nextLine();
      if( letter.equals("A") || letter.equals("B")){
        break;
      }
      System.out.println("Try again.");
    }
    System.out.println("You entered: " + letter);
 
  }
}

Output:
$ java ReadChar
Please enter a letter: a
Try again.
Please enter a letter: s
Try again.
Please enter a letter: d
Try again.
Please enter a letter: B
You entered: B

How to print a Line, Square and Triangle

Question:
Create a method called printLineOfStars(int n). Then create methods to print a Square and Triangle using the method printLineOfStars(int n).

Code:
import java.util.Scanner; 
 
public class LineOfStars {
 
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter Integer: ");
    int i = input.nextInt();
 
    System.out.println("Line:");
    printLineOfStars(i);
    System.out.println("Square:");
    printSquare(i);
    System.out.println("Triangle:");
    printTriangle(i);
 
  }
  public static void printLineOfStars(int n){
    for(int i=1;i<=n;i++){
      System.out.print("*");
    }
    System.out.println();
  }
  public static void printSquare(int n){
    for(int i=1;i<=n;i++){
      printLineOfStars(n);
    }
  }
  public static void printTriangle(int n){
    for(int i=1;i<=n;i++){
      printLineOfStars(i);
    }
  }
}

Output:
$ java LineOfStars
Enter Integer: 6
Line:
******
Square:
******
******
******
******
******
******
Triangle:
*
**
***
****
*****
******

How do you output a number that has parenthesis around it in Java?

Question:
How do you output a number that has parenthesis around it in Java?

Answer:
System.out.println ("(" + number + ")");

Code:
public class Example {
  public static void main(String[] args) {
    int number = 333;
    System.out.println("(" + number + ")");
  }
}

Output:
$ java Example
(333)

How can I do a Math.random() to generate a random number between a and b

Question:
How can I do a Math.random() to generate a random number between a and b

Code:
public class Example {
  public static void main(String[] args) {
    double a=10;
    double b=20;
    double range = b - a;
    double r = Math.random() * range + a;
    System.out.println(r);
  }
}

Output:
$ java Example 
17.09178855580154

Generating a random math operator in Java

Question:
How do I go about generating a random math operator in Java?

Answer:
By using a random number generator and a switch statement:

Code:
import java.util.Random;
 
public class SimpleMath {
 
   public static void main(String[] args) {
 
      Random r = new Random();
 
      int A = 10;
      int B = 2;
      char operator ='?';
      int value = 0;
 
      switch (r.nextInt(4)){
        case 0: operator = '+';
                value = A+B;
                break;
        case 1: operator = '-';
                value = A-B;;
                break;
        case 2: operator = '*';
                value = A*B;;
                break;
        case 3: operator = '/';
                value = A/B;;
                break;
        default: operator = '?';
      }
 
      System.out.print(A);
      System.out.print(" ");
      System.out.print(operator);
      System.out.print(" ");
      System.out.print(B);
      System.out.print(" = ");
      System.out.println(value);
   }
}

Output:
$ java SimpleMath
10 * 2 = 20

$ java SimpleMath
10 - 2 = 8

$ java SimpleMath
10 + 2 = 12

$ java SimpleMath
10 * 2 = 20

String.indexOf() using unicode as an index

Code:
public class Example {
 
   public static void main(String[] args) {
 
      String dms = "40\u00B06'8\"";
      System.out.println(dms);
 
      String str1 = dms.substring(0, dms.indexOf('\u00B0'));
      String str2 = dms.substring(dms.indexOf('\u00B0')+1,dms.indexOf('\''));
      String str3 = dms.substring(dms.indexOf('\'')+1,dms.indexOf('\"'));
      System.out.println(str1);
      System.out.println(str2);
      System.out.println(str3);
 
   }
}

Output:
$ java Example
40°6'8"
40
6
8

How to print a hollow triangle in java?

Question:
How to print a hollow triangle in java?

Code:
public class HollowTriangle {
  public static void main(String[] args) {
 
      int height = 10;  
 
      for ( int i=1 ; i<=height ; i++ ) {
         for ( int j=1 ; j <= i ; j++ ) {
            if(i==1 || i==2 || i==height || j==1 | j==i)
              System.out.print("*");
            else 
              System.out.print(" ");
         }
         System.out.println();
      }
   }
}
 

Output:
$ java HollowTriangle 
*
**
* *
*  *
*   *
*    *
*     *
*      *
*       *
**********

Hollow triangle

Question:
How do i prints hollow triangles using asterisks in java?

Code:
public class HollowTriangle {
  public static void main(String[] args) {
 
    int width = 10;
 
    for (int i = 0; i < width; i++) {
      for (int j = 0; j < width; j++) {
        if (i == 0)
          System.out.print("*");
        else if(j == i)
          System.out.print("*");
        else if(j == (width-1))
          System.out.print("*");
        else
          System.out.print(" ");
      }
      System.out.println("");
    }
  }
}

Output:
$ java HollowTriangle 
**********
 *       *
  *      *
   *     *
    *    *
     *   *
      *  *
       * *
        **
         *

Create a method which accepts an array of numbers and returns the numbers and their squares in an HashMap

Question:
Create a method which accepts an array of numbers and returns the numbers and their squares in an HashMap

Code:
import java.util.*;
 
public class Example {
 
  public static HashMap method(int[] array) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 
    for (int n: array) {
      map.put( n, n*n);
    }
    return map;
  }
 
  public static void main(String[] args) {
    int array[] = new int[]{1,2,3,4,5,6,7,8,9};
    HashMap<Integer, Integer> map = method(array);
 
    Iterator<Integer> it = map.keySet().iterator();
    while(it.hasNext()){
    Integer key = it.next();
      System.out.println(key + " : " + map.get(key));
    }
  }
}
 

Output:
$ java Example
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
9 : 81

How to print a square in java?

Question:
How to print a square in java?

Code:
import java.util.Scanner;
 
public class Square {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter Integer: ");
    int size = sc.nextInt();
    for(int i=1;i<=size;i++){
      for(int j=1;j<=size;j++){
        if(i==1||i==size|j==1||j==size){
          System.out.print("* ");
        } else {
          System.out.print("  ");
        }
      }
      System.out.println();
    }
  }
}

Output:
$ java Square
Enter Integer: 10
* * * * * * * * * * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
* * * * * * * * * * 

Split name and capitalize fist letter

Question:
Write a program that will take a string of someone's full name, and break it into separate strings of first name and last name, as well as capitalize the first letter of each. Again, use pointers and string manipulation functions only.
Example:
"joseph smith"
"Joseph"
"Smith" 

Code:
import java.util.Scanner;
 
public class Example {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter name: ");
    String name = sc.nextLine();
 
    String first = name.substring(0, name.indexOf(" "));
    String last = name.substring(name.indexOf(" ") + 1);
 
    String cap = Character.toString(first.charAt(0)).toUpperCase();
    first = cap + first.substring(1);
 
    cap = Character.toString(last.charAt(0)).toUpperCase();
    last = cap + last.substring(1);
 
    System.out.println(name);
    System.out.println(first);
    System.out.println(last);
 
  }
}
 

Output:
$ java Example
Enter name: joseph smith
joseph smith
Joseph
Smith

Sorting a parallel array

Question:
Need help sorting parallel array:
    Double [] salary = {500.00, 200.00, 1000.00, 2500.00};
    String [] name = {"Sam", "Dave", "Jake", "Ryan"}; 

Code:
public class Example {
  public static void main(String[] args) {
 
    // parallel array
    Double [] salary = {500.00, 200.00, 1000.00, 2500.00};
    String [] name = {"Sam", "Dave", "Jake", "Ryan"}; 
 
    System.out.println("Before:");
    for (int n = 0; n < name.length; n++) {
      System.out.println(name[n] + ":" + salary[n]);
    }
 
 
    int remaining = salary.length - 1;
      for(int x = 0; x < (salary.length-1); x++) {
         for(int y = 0; y < (remaining); y++) {
            double tmp1;
            String tmp2;
            if ( salary[y] > salary[y+1] ) {
 
              tmp1 =  salary[y+1]; 
              salary[y+1] = salary[y];
              salary[y] = tmp1;
 
              tmp2 =  name[y+1]; 
              name[y+1] = name[y];
              name[y] = tmp2;
 
            }
         }
         remaining--;
      }
 
    System.out.println("After:");
    for (int n = 0; n < name.length; n++) {
      System.out.println(name[n] + ":" + salary[n]);
    }
 
  }
}

Output:
$ java Example 
Before:
Sam:500.0
Dave:200.0
Jake:1000.0
Ryan:2500.0
After:
Dave:200.0
Sam:500.0
Jake:1000.0
Ryan:2500.0

Java code that will produces 1 4 9 16 25 36 49 64 81 100

Question:
Need code (a for loop in java) that will produce the output 1 4 9 16 25 36 49 64 81 100

Code:
public class Loop { 
 
  public static void main(String[] args) { 
 
    for(int i=1; i<=10; i++){
      System.out.print(i*i + " " ); 
    }
    System.out.println(""); 
  }
}
 

Output:
$ java Loop
1 4 9 16 25 36 49 64 81 100 

How to redirect standard output in a java program.

Question:
How to redirect standard output in a java program.

Code:
import java.io.*;
 
public class RedirectStandardOutput {
  public static void main(String args[]) throws FileNotFoundException {
 
    PrintStream out = new PrintStream(
      new BufferedOutputStream(
        new FileOutputStream("output.txt")));
    System.setOut(out);
 
    System.out.println("Hello World.");
    System.out.println("This is a test.");
    System.out.println("Good bye.");
 
    out.close();
  }
}

Output:
$ java RedirectStandardOutput

$ cat output.txt 
Hello World.
This is a test.
Good bye.

How to empty an ArrayList in java.

Question:
How to empty an ArrayList?

Answer:

Code:
import java.util.ArrayList;
 
public class EmptyArrayList { 
  public static void main(String[] args) { 
    ArrayList<String> list = new ArrayList<String>();
 
    list.add("John");
    list.add("Ringo");
    list.add("George");
 
    System.out.println("ArrayList: "+ list);
 
    list.add("Paul");
    System.out.println("ArrayList: "+ list);
 
    list.add("Me");
    list.clear();
    System.out.println("ArrayList: "+ list);
  } 
}
 

Output:
$ java EmptyArrayList
ArrayList: [John, Ringo, George]
ArrayList: [John, Ringo, George, Paul]
ArrayList: []

Currency conversion without multiplication or subtraction.

Question:
How to convert pesos to dollars without using multiplication or subtraction?

Code:
public class CurrencyConversion {
   public static void main(String[] args) {
 
      double rate = 0.0741;
      double pecos = 750.25;
 
      double US = pecos / (1/rate);
      System.out.println("conversion: " + US);
 
      // trick for rounding
      int dollars = (int)US;
      int cents = (int)(US/.01) % 100;
 
      System.out.println( "dollars: " + dollars);
      System.out.println( "cents: " + cents);
 
   }
}

Output:
$ java CurrencyConversion 
conversion: 55.593525
dollars: 55
cents: 59

How to draw a ChristmasTree

Question:
Using Java, write a code that creates a Christmas Tree. The code will ask user to enter a number that means the height of the tree.

Code:
import java.util.Scanner;
 
public class ChristmasTree {
 
   public static void main(String args[]) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.print("Enter height: ");
      int height = sc.nextInt();
 
      for (int i = 0; i < height; ++i) {
  for (int j = -height + 1; j < -i; ++j) {
     System.out.print(" ");
  }
  for (int j = -i; j <= i; ++j) {
     if (j == 0) {
        System.out.print("|");
     } else if (j < 0) {
        System.out.print("\\");
     } else {
        System.out.print("/");
     }
  }
  System.out.println("");
      }
   }
}

Output:
$ java ChristmasTree
Enter height: 10
         |
        \|/
       \\|//
      \\\|///
     \\\\|////
    \\\\\|/////
   \\\\\\|//////
  \\\\\\\|///////
 \\\\\\\\|////////
\\\\\\\\\|/////////

List of divisors for a given input

Question:
Java code to find the divisors of a given number? such as: entering six, and getting 1,2,3,6 as output?

Code:
import java.util.Scanner;
 
public class Divisors {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter number: ");
      int n = sc.nextInt();;
 
      System.out.print(1);
      for (int i = 2; i <= n; i++) {
         if (n % i == 0) {
            System.out.print("," + i);
         }
      }
      System.out.println();
   }
}

Output:
$ java Divisors
Enter number: 6
1,2,3,6

Find consecutive duplicate numbers in a series of numbers seperated by commas

Question:
Find consecutive duplicate numbers in a series of numbers seperated by commas?

Code:
import java.util.Scanner;
 
public class DuplicateNumbers {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    // Example: 1,2,3,4,3,2,1
    System.out.print("Enter numbers: ");
    String str = sc.nextLine();
 
    // splitting a comma separated string
    String[] numbers = str.split(",");
 
    Integer last = null;
    Integer current = null;
    int total = 0;
 
    for (String number: numbers) {
 
      current = Integer.parseInt(number);
 
      // if last is null then this is the first number
      if (last != null) {
        if(last == current){
          System.out.println("Duplicates: " + current);
          total = total +1;
        }
      }
      last = current;
 
    }
    System.out.println("Total duplicates: " + total);
  }
}

Output:
$ java DuplicateNumbers
Enter numbers: 1,2,5,5,7,8,8,4,4,3,2,1
Duplicates: 5
Duplicates: 8
Duplicates: 4
Total duplicates: 3

Type in multiple names and numbers, store and display afterwards.

Question:
I want to be able to type in some names and their numbers into my java app and when they're typed in for them to be stored and displayed afterwards on screen. How is this possible? Thanks!

Answer:
By using a scanner and a parallel array.

Code:
import java.util.Scanner;
 
public class NameAndNumbers {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      int count = 5;
 
      String name[] = new String[count];
      int number[] = new int[count];
 
      for (int i=0; i<count;i++){
        System.out.print("Enter name: ");
        name[i] = sc.nextLine();
 
        System.out.print("Enter number: ");
        number[i] = Integer.parseInt(sc.nextLine());
      }
 
      System.out.println("Output:");
      for (int i=0; i<count;i++){
        System.out.println(name[i] + " " + number[i]);
      }
   }
}

Output:
$ java NameAndNumbers
Enter name: Tom Jones
Enter number: 11
Enter name: Tom Sawyer
Enter number: 33
Enter name: Tom Brady
Enter number: 12
Enter name: Tom Cruise
Enter number: 55
Enter name: Tom Hanks
Enter number: 100
Output:
Tom Jones 11
Tom Sawyer 33
Tom Brady 12
Tom Cruise 55
Tom Hanks 100