Showing posts with label if-else. Show all posts
Showing posts with label if-else. Show all posts

Counting Vowels and Non-vowel Characters in Java

Problem:

Write a class Vowels that reads a one-line statement from the user, then determines and prints how many of each vowel (A/a, E/e, 1/i, 0/o, and U/u) and many non-vowel character appear in the entire statement. You need a separate counter for each vowel and one counter for the non-vowel characters. You need to use the switch statement to determine the vowel characters.

Output:

Please enter a statement: Hello my name is Amer

The number of "A"s (lower and upper case) is: 2
The number of "E"s (lower and upper case) is: 6
The number of "I"s (lower and upper case) is: 1
The number of "0"s (lower and upper case) is: 1
The number of "U"s (lower and upper case) is: 0

The number of non-vowels is: 7

Solution:

import java.util.Scanner;
public class Problem2
{
    public static void main(String args[]) 
    {
     Scanner scan = new Scanner(System.in);
     System.out.println("Please enter a statement:");
     String statement = scan.nextLine();
     int i = 0;
     
     int vowelAcount = 0;
     int vowelEcount = 0;
     int vowelIcount = 0;
     int vowelOcount = 0;
     int vowelUcount = 0;
     int nonvowel= 0;
        int spacescount = 0;
     
     while (i < statement.length())
     {
            char chararcter = statement.charAt(i++);
            switch (chararcter)
            {
                case 'A': 
                case 'a':
                    vowelAcount++;
                    break;
        
      case 'E': 
                case 'e':
                    vowelEcount++;
                    break;
       
      case 'I': 
                case 'i':
                    vowelIcount++;
                    break;
      
                case 'O': 
                case 'o':
                    vowelOcount++;
                    break;
        
                case 'U': 
                case 'u':
                    vowelUcount++;
                    break;
      
                case ' ':
                    spacescount++;
                    break;
                
                default:
                    nonvowel++;
                    break;
        
            }
     
     }
     
     System.out.println("The number of As (lower and upper case) is : "+ vowelAcount);
     System.out.println("The number of Es (lower and upper case) is : "+ vowelEcount);
     System.out.println("The number of Is (lower and upper case) is : "+ vowelIcount);
     System.out.println("The number of Os (lower and upper case) is : "+ vowelOcount);
     System.out.println("The number of Us (lower and upper case) is : "+ vowelUcount);
     System.out.println("The number of non-vowels is : " + nonvowel);
     
    }
    
}
Read More

Creating a Guessing Game in Java

Problem:

Write a class GuessingGame that simulates a simple guessing game. Initially, your program should generate a random integer between 1 and 1000 and print the following: "Guess the number between 1 and 1000" (without the quotes). Then, the user is asked to guess the number generated. If the user is correct, the program prints:
"Congratulations" (without the quotes).
Otherwise, if the number entered by the user is less than the generated number you print "Too cold" and when the number is above you print "Too hot". The game does not stop until the user has made a correct guess. Sample program output:

Output:

Guess the number between 1 and 1000

500

Too Cold

750

Too Hot
600
Congratulations

Solution:

import java.util.*;
public class Problem1
{
    public static void main (String args[])
    {
 Random random = new Random();
 int a = random.nextInt(1000) + 1;
 Scanner scan = new Scanner(System.in);
 int guess = 0;
 while (a != guess)
 {
            System.out.println("Guess the number between 1 and 1000:");
            guess = scan.nextInt();
            if (guess < a)
  System.out.println("Too cold!");
            else
  System.out.println("Too hot!");
 }
 if (a == guess)
            System.out.println("Congratulations!");
   
    }
}
Read More

Generating Phone Number in Java

Problem:

Write an application that creates and prints a random phone number of the form xxx-xxx-xxxx. Include the dashed in the output. Do not let the first three digits contain an 8 or 9. And make sure that the second set of three digits is not greater than 742 (i.e. ≤ 742). Hint: Think through the easiest way to construct he phone number. Each digit does not have to be determined separately.

Output:

016-326-5981

Solution:

import java.util.Random;
public class Problem4 {

   public static void main(String args[])
   {
     Random generator = new Random();


     // Generate 3 random numbers between 0 & 7 for the first part of the phone number
  int one = generator.nextInt(8);
  int two = generator.nextInt(8);
  int three = generator.nextInt(8);
  int fourtosix = generator.nextInt(743);
  int seventoten = generator.nextInt(10000);
  String sOne = "" + (one);
  String sTwo = "" + (two);
  String sThree = "" + (three);
  String sFourtosix = "";
  String sSeventoten = "";
  if (fourtosix >= 0 && fourtosix < 10)
   sFourtosix = "00" + (fourtosix);
   else
    if(fourtosix < 100)
     sFourtosix = "0" + (fourtosix);
    else
     sFourtosix = "" + (fourtosix);
     
  if (seventoten >= 0 && seventoten < 10)
   sSeventoten = "000" + (seventoten);
   else
    if(seventoten < 100)
     sSeventoten = "00" + (seventoten);
    else
     if(seventoten < 1000)
      sSeventoten = "0" + (seventoten);
      else
       sSeventoten = "" + (seventoten);  
 

  //Print the phonenumber with this format xxx-xxx-xxxx
  System.out.printf(sOne + sTwo + sThree +"-" +sFourtosix + "-" + sSeventoten);
   }


}
Read More

Rolling Dices through Random Class in Java

Problem:

Nour and Jad start-out the game with a cumulative score of zero. Then each player rolls three dices and a random number appears for each dice. The summation of each number is added in each player’s score. The winner is the player that has the highest score in x turns based on what the players initially decided. Note: If Jad’s score and Nour’s score are equal, let the program prints: Jad and Nour have equal scores, else let the program print who is the winner.

The output should be as follows:

Output:

Please enter the number of turns:
3
Jad's score is: 26
Nour's score is: 27
Nour is the winner

Solution:

import java.util.Random;
import java.util.Scanner;
/**
 *
 * @author George Chalhoub
 */
public class Problem3 {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        Random randomdice = new Random();
     
        int sumjad = 0;
        int sumnour = 0;
   
        int jadDice1 = randomdice.nextInt(7);
        int jadDice2 = randomdice.nextInt(7);
        int jadDice3 = randomdice.nextInt(7);
        int nourDice1 = randomdice.nextInt(7);
        int nourDice2 = randomdice.nextInt(7);
        int nourDice3 = randomdice.nextInt(7);
        sumjad = sumjad + jadDice1 + jadDice2 + jadDice3;
        sumnour = sumnour + nourDice1 + nourDice2 + nourDice3;
     
        System.out.println("Jad's score is: " + sumjad);
        System.out.println("Nour's score is: " + sumnour);
        if (sumjad == sumnour)
                System.out.println("Jad and Nour have the same scores");
        else
            if (sumjad > sumnour)
                System.out.println("Jad is the winner");
                else
                    System.out.println("Nour is the winner");
    }
    
}

    
Read More

How to Represent a Month Value from Numbers in Java

Problem:

Write a program that would read an input from the user that represents the month value. Then the code will display the name of the month based on this value, using the switch statement. For example, if the user input is:

Output:

Please enter the month number:
4

The month selected is: APRIL

Solution:

import java.util.Scanner;

public class Problem2 {
     public static void main(String[] args) {
           Scanner input = new Scanner(System.in);
           System.out.println( "Please enter the number of the month:");
           int monthvalue = input.nextInt();
           String month;
           switch(monthvalue){
               case 1: month = "January";
                   break;
               case 2: month = "February";
                   break;
               case 3: month = "March";
                   break;
               case 4: month = "April";
                   break;
               case 5: month = "May";
                   break;
               case 6: month = "June";
                   break;
               case 7: month = "July";
                   break;
               case 8: month = "August";
                   break;
               case 9: month = "September";
                   break;
               case 10: month = "October";
                   break;
               case 11: month = "November";
                   break;
               case 12: month = "December";
                   break;
               default: month = "Invalid Month";
                   break;
           }
         
           System.out.println(month);
     }
}
Read More

Legal Age Calculator in Java

Problem:

Write a program that takes the name and the age of the user. The program should check the age of the user and then prints out if the person can get his driver license or not.
If the age is under 18 then you should print “ ……. Too young to get his/her driving license”
If the age is greater than or equal to 18 then the program should print “……. can have his/her Driving License”.
The program should look as follows:
Enter Name:
Talal
Enter Age:
16
Talal is too young to get his driving License

Solution:

/**
 * @(#)Problem3.java
 *
 *
 * @author George Chalhoub
 * @version 1.00 2012/10/16
 */

import java.util.Scanner;
public class Problem3 {

   public static void main(String args[])
   {
    Scanner input=new Scanner(System.in);
    
    System.out.print("Enter name:");
    String name=input.nextLine();
    System.out.print("Enter Age:");
    int age=input.nextInt();
    
    if (age<18)
     System.out.print(name+" is too young to get his/her driving license");
    else
       System.out.print(name+" can get his/her driver license");
   }
    
}
Read More

Java > AP-1 > userCompare (CodingBat Solution)

Problem:

We have data for two users, A and B, each with a String name and an int id. The goal is to order the users such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same. Order first by the string names, and then by the id numbers if the names are the same. Note: with Strings str1.compareTo(str2) returns an int value which is negative/0/positive to indicate how str1 is ordered to str2 (the value is not limited to -1/0/1). (On the AP, there would be two User objects, but here the code simply takes the two strings and two ints directly. The code logic is the same.)

userCompare("bb", 1, "zz", 2) → -1
userCompare("bb", 1, "aa", 2) → 1
userCompare("bb", 1, "bb", 1) → 0


Solution:

public int userCompare(String aName, int aId, String bName, int bId) {
  if (aName.equals(bName) && aId == bId)
    return 0;
  
  int result = aName.compareTo(bName);
  if (result < 0)
    return -1;
  else if (result > 0)
    return 1;
  else if (aId > bId)
    return 1;
  else
    return -1;
    
}
Read More

Java > Logic-1 > sumLimit (CodingBat Solution)

Problem:

Given 2 non-negative ints, a and b, return their sum, so long as the sum has the same number of digits as a. If the sum has more digits than a, just return a without b. (Note: one way to compute the number of digits of a non-negative int n is to convert it to a string with String.valueOf(n) and then check the length of the string.)

sumLimit(2, 3) → 5
sumLimit(8, 3) → 8
sumLimit(8, 1) → 9


Solution:

public int sumLimit(int a, int b) {
  String aString = String.valueOf(a);
  int aLen = aString.length();
  String sumString = String.valueOf(a+b);
  int sumLen = sumString.length();
  
  if (sumLen == aLen)
    return a + b;
  else
    return a;
  
}
Read More

Java > Logic-1 > shareDigit (CodingBat Solution)

Problem:

Given two ints, each in the range 10..99, return true if there is a digit that appears in both numbers, such as the 2 in 12 and 23. (Note: division, e.g. n/10, gives the left digit while the % "mod" n%10 gives the right digit.)

shareDigit(12, 23) → true
shareDigit(12, 43) → false
shareDigit(12, 44) → false


Solution:

public boolean shareDigit(int a, int b) {
  int aL = a / 10;
  int aR = a % 10;
  int bL = b / 10;
  int bR = b % 10;
  
  if (aL == bL || aL == bR || aR == bL || aR == bR)
    return true;
  else
    return false;
}
Read More

Java > Logic-1 > blueTicket (CodingBat Solution)

Problem:

You have a blue lottery ticket, with ints a, b, and c on it. This makes three pairs, which we'll call ab, bc, and ac. Consider the sum of the numbers in each pair. If any pair sums to exactly 10, the result is 10. Otherwise if the ab sum is exactly 10 more than either bc or ac sums, the result is 5. Otherwise the result is 0.

blueTicket(9, 1, 0) → 10
blueTicket(9, 2, 0) → 0
blueTicket(6, 1, 4) → 10


Solution:

public int blueTicket(int a, int b, int c) {
  int ab = a + b;
  int bc = b + c;
  int ac = a + c;
  
  if (ab == 10 || bc == 10 || ac == 10)
    return 10;
  if (ab - bc == 10 || ab - ac == 10)
    return 5;
  else
    return 0;
}
Read More

Java > Logic-1 > greenTicket (CodingBat Solution)

Problem:

You have a green lottery ticket, with ints a, b, and c on it. If the numbers are all different from each other, the result is 0. If all of the numbers are the same, the result is 20. If two of the numbers are the same, the result is 10.

greenTicket(1, 2, 3) → 0
greenTicket(2, 2, 2) → 20
greenTicket(1, 1, 2) → 10


Solution:

public int greenTicket(int a, int b, int c) {
  if (a == b && b == c)
    return 20;
  if (a == b || a == c || b == c)
    return 10;
  else;
    return 0;
}
Read More

Java > Logic-1 > redTicket (CodingBat Solution)

Problem:

You have a red lottery ticket showing ints a, b, and c, each of which is 0, 1, or 2. If they are all the value 2, the result is 10. Otherwise if they are all the same, the result is 5. Otherwise so long as both b and c are different from a, the result is 1. Otherwise the result is 0.

redTicket(2, 2, 2) → 10
redTicket(2, 2, 1) → 0
redTicket(0, 0, 0) → 5


Solution:

public int redTicket(int a, int b, int c) {
  if (a == 2 && b == 2 && c == 2)
    return 10;
  if ( a == b && b == c)
    return 5;
  if ( a != b && a != c)
    return 1;
  else
    return 0;
}
Read More

Java > Logic-1 > maxMod5 (CodingBat Solution)

Problem:

Given two int values, return whichever value is larger. However if the two values have the same remainder when divided by 5, then the return the smaller value. However, in all cases, if the two values are the same, return 0. Note: the % "mod" operator computes the remainder, e.g. 7 % 5 is 2.

maxMod5(2, 3) → 3
maxMod5(6, 2) → 6
maxMod5(3, 2) → 3


Solution:

public int maxMod5(int a, int b) {
  if (a == b)
    return 0;
    
  if (a % 5 == b % 5)
    return Math.min(a,b);
  
  return Math.max(a,b);
}
Read More

Java > Logic-1 > withoutDoubles (CodingBat Solution)

Problem:

Return the sum of two 6-sided dice rolls, each in the range 1..6. However, if noDoubles is true, if the two dice show the same value, increment one die to the next value, wrapping around to 1 if its value was 6.

withoutDoubles(2, 3, true) → 5
withoutDoubles(3, 3, true) → 7
withoutDoubles(3, 3, false) → 6


Solution:

public int withoutDoubles(int die1, int die2, boolean noDoubles) {
  if(noDoubles) {
    if (die1 == die2) {
      if (die1 != 6)
        return die1 + 1 + die2;
      else
        return 1 + die2;
    } 
  }
  
  return die1 + die2;
    
}
Read More

Java > Logic-1 > lessBy10 (CodingBat Solution)

Problem:

Given three ints, a b c, return true if one of them is 10 or more less than one of the others.

lessBy10(1, 7, 11) → true
lessBy10(1, 7, 10) → false
lessBy10(11, 1, 7) → true


Solution:

public boolean lessBy10(int a, int b, int c) {
  int high = Math.max(a,b);
  high = Math.max(high, c);
  
  if (high - a >= 10 || high - b >= 10 || high - c >=10)
    return true;
  else 
    return false;
}
Read More

Java > Logic-1 > lastDigit (CodingBat Solution)

Problem:

Given three ints, a b c, return true if two or more of them have the same rightmost digit. The ints are non-negative. Note: the % "mod" operator computes the remainder, e.g. 17 % 10 is 7.

lastDigit(23, 19, 13) → true
lastDigit(23, 19, 12) → false
lastDigit(23, 19, 3) → true


Solution:

public boolean lastDigit(int a, int b, int c) {
  int modA = a % 10;
  int modB = b % 10;
  int modC = c % 10;
  
  if (modA == modB || modA == modC || modB == modC)
    return true;
  else
    return false;
}
Read More

Java > Logic-1 > inOrderEqual (CodingBat Solution)

Problem:

Given three ints, a b c, return true if they are in strict increasing order, such as 2 5 11, or 5 6 7, but not 6 5 7 or 5 5 7. However, with the exception that if "equalOk" is true, equality is allowed, such as 5 5 7 or 5 5 5.

inOrderEqual(2, 5, 11, false) → true
inOrderEqual(5, 7, 6, false) → false
inOrderEqual(5, 5, 7, true) → true


Solution:

public boolean inOrderEqual(int a, int b, int c, boolean equalOk) {
  if (!equalOk && a < b && b < c)
    return true;
  if (equalOk && a <= b && b <= c)
    return true;
  else
    return false;
}
Read More

Java > Logic-1 > inOrder (CodingBat Solution)

Problem:

Given three ints, a b c, return true if b is greater than a, and c is greater than b. However, with the exception that if "bOk" is true, b does not need to be greater than a.

inOrder(1, 2, 4, false) → true
inOrder(1, 2, 1, false) → false
inOrder(1, 1, 2, true) → true


Solution:

public boolean inOrder(int a, int b, int c, boolean bOk) {
  if(bOk) {
    if (c > b)
      return true;
    else
      return false;
  }
  if (b > a && c > b)
    return true;
  else
    return false;
}
Read More

Java > Logic-1 > twoAsOne (CodingBat Solution)

Problem:

Given three ints, a b c, return true if it is possible to add two of the ints to get the third.

twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false


Solution:

public boolean twoAsOne(int a, int b, int c) {
  if ( a + b == c || c + b == a || c + a == b)
    return true;
  else
    return false;
}
Read More

Java > Logic-1 > fizzString2 (CodingBat Solution)

Problem:

Given an int n, return the string form of the number followed by "!". So the int 6 yields "6!". Except if the number is divisible by 3 use "Fizz" instead of the number, and if the number is divisible by 5 use "Buzz", and if divisible by both 3 and 5, use "FizzBuzz". Note: the % "mod" operator computes the remainder after division, so 23 % 10 yields 3. What will the remainder be when one number divides evenly into another? (See also: FizzBuzz Code and Introduction to Mod)

fizzString2(1) → "1!"
fizzString2(2) → "2!"
fizzString2(3) → "Fizz!"


Solution:

public String fizzString2(int n) {
    boolean fizz = n % 3 == 0;
    boolean buzz = n % 5 == 0;
 
    if (fizz && buzz) return "FizzBuzz!";
    if (fizz) return "Fizz!";
    if (buzz) return "Buzz!";
    return n + "!";
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact