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) {
  if(a+b == 10 || b+c == 10 || a+c == 10)
  return 10;
  else if (a+b == (10 + b+c) ||  a+b == (10 + a+c) )
  return 5;
  else
  return 0;
}
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 str = Integer.toString(a+b);
String str2 = Integer.toString(a);

if(str.length() == str2.length())
return a+b;
else 
return a;
  
}
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 ( Math.abs(a - b) == Math.abs(c) || Math.abs(a + b) == Math.abs(c) )
  return true;
  else 
  return false; 
}
Read More

Creating Book Class in Java

Problem:

Write a class named Book that keeps track of book objects such that the instance data contains the book’s title and author and a unique identification number, say id that starts form 1 for the first book object and is incremented by 1 each time a new book with at least the title specified is created. The required methods in the Book class are as follows:

  • 3 constructors: One without parameters that sets the title and author to “unknown” and id to 0; one with a single parameter that sets the title to the given value as parameter, sets the author to “unknown”, increments the sequence by 1 and sets id to this sequence number; one with two parameters for title and author, setting the corresponding instance data, and id as in the second constructor.
  • The setter methods for title and author.
  • The getter methods for title, author, and id.
  • The equals method that compares the current book object with another Book object given as a parameter and returns true if both objects have the same title and author properties, and false otherwise.
  • The toString method that returns a text including the book’s title, author and id. Refer to the sample execution window for the test program for details.
  • The getInitials method that returns the initial letters of the author’s first name(s) and last name, if the author’s name is known (not equal to “unknown”, or not null).Assume that there can be at most two names and one surname separated by a single blank. Refer to the sample execution window for the test program for details.

Write a driver class that tests the Book class. Allow the user to enter as many book objects as s/he wants. Take care of necessary object initializations. Store the first and last book objects separately. Print each book object. Compare the first and last book objects, if any, and display a proper message if they are the same. Display the last book’s author’s initials, if the user has input any valid book object.

Sample execution windows:
To end the input process bypass each question by typing the enter key!
Type the title of the book:
Type the name of the author:
Press any key to continue...

To end the input process bypass each question by typing the enter key!
Type the title of the book: Windows NT Server 4.0
Type the name of the author: Russel
Book No: 1 entitled "Windows NT Server 4.0" written by Russel
Type the title of the book:
Type the name of the author:
First and last books are same
Last book's author has the initials, R.
Press any key to continue...

To end the input process bypass each question by typing the enter key!
Type the title of the book: Java Software Solutions
Type the name of the author: Lewis Loftus
Book No: 1 entitled "Java Software Solutions" written by Lewis Loftus
Type the title of the book: Introduction to Java Programming with JBuilder
Type the name of the author: Yvet Daniel Liang
Book No: 2 entitled "Introduction to Java Programming with JBuilder" written by
Yvet Daniel Liang
Type the title of the book:
Type the name of the author:
Last book's author has the initials, Y.D.L.
Press any key to continue...

Solution:

public class Book
{
 private String author, title;
 private int id;
 private static int identification =0;
 
 public Book()
 {
  title = author = "unknown";
  id = 0;
 }
 public Book(String title)
 {
  this.title = title;
  author = "unknown";
  identification++;
  id = identification;
 }
 public Book (String title, String author)
 {
  this.title = title;
  this.author = author;
  identification++;
  id = identification;
 }
 
 public void setTitle(String title)
 {
  this.title = title;
 }
 
 public void setAuthor(String author)
 {
  this.author = author;
 }
 
 public String getTitle()
 {
  return title;
 }
 public String getAuthor()
 {
  return author;
 }
 public int getId()
 {
  return id;
 }
 
 public boolean equals(Book other)
 {
  boolean enough = true;
  String otherAuthor = other.getAuthor();
  String otherTitle = other.getTitle();
  if(otherAuthor.equals(author) && otherTitle.equals(title))
   enough = true;
  else 
   enough = false;
  return enough;
 }
 public String getInitials ()
 {
  String output = "";
  if (!(author.equals("")) && !
          (author.equals("unknown")) && !(author.equals(null))) {
   output += author.charAt(0);
   output += ". ";
   if (author.indexOf(" ") != -1) {
   output += author.charAt(author.indexOf(" ") + 1);
   output += ". "; }
   
   if (author.indexOf(" ") != -1) {
   output += author.charAt((author.indexOf(" ") 
                         + author.indexOf(" ")) +4 );
   output += ". "; }
  }
  return output;
 }
 public String toString()
 {
  return "Book No: " + id + " entitled \"" 
                + title + "\"" + " written by " + author;
 }
}
import java.util.Scanner;
public class BookTest
{
 public static void main (String[] args)
 {
  Book firstBook = new Book();
        Book lastBook = new Book();
        Book aBook = new Book();
        
  Scanner scan = new Scanner (System.in);
  System.out.println("To end the input " +
       "process bypass each question by typing the enter key!");
  System.out.print("Type the title of the book: ");
  String title = scan.nextLine();
  System.out.print("Type the name of the author: ");
  String author = scan.nextLine();
  
  aBook = new Book(title, author);

  if (!(title.equals("") && author.equals("")))
  System.out.println(aBook);
  
  while (!(title.equals("") && author.equals("")))
  {
    if (aBook.getId() == 1)
     firstBook = aBook;
    System.out.print("Type the title of the book: ");
    title = scan.nextLine();
    System.out.print("Type the name of the author: ");
    author = scan.nextLine();
    if (!(title.equals("") && author.equals(""))) {  
     aBook = new Book(title, author);
    System.out.print(aBook);
    System.out.println(); }
  }
  lastBook = aBook;
  if (firstBook.equals(lastBook))
   System.out.println("First and last books are the same");
  System.out.println(lastBook.getInitials());
    
  
 }
}
Read More

Project Euler > Problem 46 > Goldbach's other conjecture (Java Solution)

Problem:

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.

9 = 7 + 2[×]12
15 = 7 + 2[×]22
21 = 3 + 2[×]32
25 = 7 + 2[×]32
27 = 19 + 2[×]22
33 = 31 + 2[×]12

It turns out that the conjecture was false.

What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?


Solution:

5777


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 46
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p046 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p046().run());
 }
 
 
 public String run() {
  for (int i = 2; ; i++) {
   if (!satisfiesConjecture(i))
    return Integer.toString(i);
  }
 }
 
 
 private boolean satisfiesConjecture(int n) {
  if (n % 2 == 0 || isPrime(n))
   return true;
  
  // Now n is an odd composite number
  for (int i = 1; i * i * 2 <= n; i++) {
   if (isPrime(n - i * i * 2))
    return true;
  }
  return false;
 }
 
 
 private boolean[] isPrime = {};
 
 private boolean isPrime(int n) {
  if (n >= isPrime.length)
   isPrime = Library.listPrimality(n * 2);
  return isPrime[n];
 }
 
}
Read More

Java > String-2>xyzMiddle (CodingBat Solution)

Problem:

Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one. This problem is harder than it looks.

xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false


Solution:

public boolean xyzMiddle(String str)
{   
int p = (str.length() - 3) / 2;   
return (p >= 0) && 
   str.substring(p, str.length() - p).matches(".?xyz.?");
}
Read More

Java > Logic-2 >loneSum (CodingBat Solution)

Problem:

Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.

loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0


Solution:

public int loneSum(int a, int b, int c) {
  if(a ==b && b == c) {
  a=0;b=0;c=0; }
  if (a==b){
  a = 0; b = 0;}
  if (a==c){
  a=0;c=0;}
  if(b==c) {
  b=0;c=0; }

  return a+b+c;
}
Read More

Java > Logic-2 >evenlySpaced (CodingBat Solution)

Problem:

Given three ints, a b c, one of them is small, one is medium and one is large. Return true if the three values are evenly spaced, so the difference between small and medium is the same as the difference between medium and large.

evenlySpaced(2, 4, 6) → true
evenlySpaced(4, 6, 2) → true
evenlySpaced(4, 6, 3) → false


Solution:

public boolean evenlySpaced(int a, int b, int c) {
int diff1 = 0;
int diff2 = 0;
int diff3 = 0;

if(a==b && a ==c)
return true;

if(a == b || b == c || a == c)
return false; 

diff1 = Math.abs(a - b); 
diff2 = Math.abs(a - c); 
diff3 = Math.abs(b - c); 

if(diff1 == diff2)
return true;
if(diff1 == diff3)
return true;
if(diff2 == diff3)
return true;

return false;
}

Read More

Java > Logic-2 >luckySum (CodingBat Solution)

Problem:

Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.

luckySum(1, 2, 3) → 6
luckySum(1, 2, 13) → 3
luckySum(1, 13, 3) → 1


Solution:

public int luckySum(int a, int b, int c) {
  if (a == 13)
 { a = 0; b =0; c =0; }
  if (b == 13)
 { b=0; c=0; }
  if (c == 13)
 { c=0; }
  return a + b + c;
}
Read More

Java > Logic-2 >blackJack (CodingBat Solution)

Problem:

Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.

blackjack(19, 21) → 21
blackjack(21, 19) → 21
blackjack(19, 22) → 19


Solution:

public int blackjack(int a, int b) {
int output=0;
if ( a > 21)
a=0;
if ( b>21)
b=0;
if ( a > b )
output = a;
else if (b>a)
output = b;

return output;
    
}
Read More

Java > Logic-2 >noTeenSum (CodingBat Solution)

Problem:

Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "public int fixTeen(int n) {"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main noTeenSum().


Solution:

public int noTeenSum(int a, int b, int c) {
int RETURN = 0;
  if ( a == 13 || a == 14 || a == 17 || a == 18 || a == 19)
    a= 0;
      if ( b == 13 || b == 14 || b == 17 || b == 18 || b == 19)
    b= 0;
      if ( c == 13 || c == 14 || c == 17 || c == 18 || c == 19)
    c= 0;
    
    return a + b + c;
  
}
Read More

Java > String-2 >countHi (CodingBat Solution)

Problem:

Return the number of times that the string "hi" appears anywhere in the given string.

countHi("abc hi ho") → 1
countHi("ABChi hi") → 2
countHi("hihi") → 2


Solution:

public int countHi(String str) {
int count =0;
  if (str.length() ==1 && str.charAt(0) == 'h')
  count = 0;
  else
  {
  for(int i = 0;i<str.length();i++) {
    if ( (str.charAt(i) == 'h') && (str.charAt(i+1) == 'i') )
     count+=1; 
     }
     }
     return count;
}
Read More

Java > String-2 >doubleChar (CodingBat Solution)

Problem:

Given a string, return a string where for every char in the original, there are two chars.

doubleChar("The") → "TThhee"
doubleChar("AAbb") → "AAAAbbbb"doubleChar("Hi-There") → "HHii--TThheerree"


Solution:

public String doubleChar(String str) {
String love = "";
    for (int i = 0; i <=str.length()-1;i++) {
           love += str.charAt(i);
           love += str.charAt(i); }
           return love;
}

Read More

Java > Warmup-1 >sleepIn (CodingBat Solution)

Problem:

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in.

sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true


Solution:

public boolean sleepIn(boolean weekday, boolean vacation) {
boolean DONE = false;
if (!weekday || vacation)
DONE = true;
  return DONE;
}
}
Read More

Java > Warmup-1 >startOz (CodingBat Solution)

Problem:

Given a string, return a string made of the first 2 chars (if present), however include first char only if it is 'o' and include the second only if it is 'z', so "ozymandias" yields "oz".

startOz("ozymandias") → "oz"
startOz("bzoo") → "z"
startOz("oxx") → "o"


Solution:

public String startOz(String str) {
if ( str.length() == 1)
  str = str.substring(0,1);
  else if (str.length() == 0)
  str = "";
else if ( !(str.charAt(0) == 'o') && !(str.charAt(1) ==
  'z') )
   str = "";
   else if ( str.charAt(0) == 'o' && str.charAt(1) != 'z')
   str = str.substring(0,1);
   else if (str.charAt(1) == 'z' && str.charAt(0) != 'o')
   str = str.substring(1,2);
   else if ( str.charAt(0) =='o' && str.charAt(1) == 'z')
   str = str.substring(0,2);
   return str;
 
}
Read More

Java > Warmup-1 >icyHot (CodingBat Solution)

Problem:

Given two temperatures, return true if one is less than 0 and the other is greater than 100.

icyHot(120, -1) → true
icyHot(-1, 120) → true
icyHot(2, 120) → false


Solution:

public boolean icyHot(int temp1, int temp2) {
boolean value = false;
  if ( temp1 < 0 && temp2 > 100  || temp2 <0 && temp1 > 100)
        value = true;
   return value;
}


Read More

Java > Warmup-1 >frontBack (CodingBat Solution)

Problem:

Given a string, return a new string where the first and last chars have been exchanged.

frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"


Solution:

public String frontBack(String str) {
   if (str.length() == 1 || str.length() == 0 )
        return str;
        else
return str = (str.substring(str.length()-1,str.length()) + 
   str.substring(1,str.length()-1) + str.substring(0,1));
}
Read More

Java > Warmup-1 >backAround (CodingBat Solultion)

Problem:

Given a string, take the last char and return a new string with the last char added at the front and back, so "cat" yields "tcatt". The original string will be length 1 or more.

backAround("cat") → "tcatt"
backAround("Hello") → "oHelloo"
backAround("a") → "aaa"


Solution:

public String backAround(String str) {
  return str.charAt(str.length() -1) 
    + str + str.charAt(str.length() -1);
}
Read More

Java > Warmup-1 >diff21 (CodingBat Solution)

Problem:

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.

diff21(19) → 2
diff21(10) → 11
diff21(21) → 0


Solution:

public int diff21(int n) {
int OUTPUT = 0;
  if (n > 21)
     OUTPUT = Math.abs((21 - n)*2);
     else OUTPUT = Math.abs(21 - n);
     return OUTPUT;
}
Read More

Java > Warmup-1 >nearHundred (CodingBat Solutions)

Problem:

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

nearHundred(93) → true
nearHundred(90) → true
nearHundred(89) → false


Solution:

public boolean nearHundred(int n) {
boolean ANSWER = false;
if ( n + 10 >= 100 && n - 10 <= 100)
       ANSWER = true;
       else if ( n + 10 >= 200 && n - 10 <=200)
       ANSWER = true;
return ANSWER;
 
}
Read More

Java > Warmup-1 > max1020 (CodingBat Solution)

Problem:

Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range.

max1020(11, 19) → 19
max1020(19, 11) → 19
max1020(11, 9) → 11


Solution:

public int max1020(int a, int b) {
int OUTPUT =0;
if (a >= 10 && b <=20)
{
 if (a > b )OUTPUT = a;
   else if (b > a) OUTPUT = b;
  
   }
  
    // (10 <= a <= 20)  and   (b > 20 or b < 10)  return a;
    //( a > 20 or a < 20) and (10<=b <=20 return b;
   
   if ( (10 <= a && a <=20) && (b>20 || b < 10) )
        OUTPUT = a;
   if ( ( a > 20 || a <10) && (10 <=b && b <= 20) )
        OUTPUT = b;
       
        return OUTPUT;
         }
Read More

Java > Warmup-1 > intMax (CodingBat Solution)

Problem:

Given three int values, a b c, return the largest.

intMax(1, 2, 3) → 3
intMax(1, 3, 2) → 3
intMax(3, 2, 1) → 3


Solution:

public int intMax(int a, int b, int c) {
int MAX = a;
if ( b > MAX) MAX = b;
if ( c >MAX) MAX = c;
return MAX;
}
Read More

Java > Warmup-1 > missingChar (CodingBat Solution)

Problem:

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).

missingChar("kitten", 1) → "ktten"
missingChar("kitten", 0) → "itten"
missingChar("kitten", 4) → "kittn"


Solution:

//Well, we can make do with just creating a method
//that will return us a modified string that will take
//in our String and index
public String missingChar(String str, int n) {
  //We can't remove things from a String variable, just add
  //to it so we have to make a new string by taking two
  //'slices' or substrings of that String but without including
  //a certain index.
  //Note: str.substring(a,b) gives us a new String starting
  //from index 0 to index b-1, which is why n isn't in the new
  //string and why length() doesn't cause any problems
  return str.substring(0,n) + str.substring(n+1,str.length());
     }
Read More

Creating Dog Class In Java

Problem:

Design and implement a class called Dog that contains instance data that represents the dog’s name and age. Define the Dog constructor to accept and initialize instance data. Include getter and setter methods for the name and age. Include a method to compute and return the age of the dog in “person years” (seven times the dogs age). Include a toString method that returns a one-line description of the dog. Create a driver class called Kennel, whose main method instantiates and updates several Dog objects.

Solution:

public class Dog
{
 private int age;
 private String name; 
 public Dog(int age,String name)
 {
  this.age = age;
  this.name = name;
 }
 
 public String setDogName(String name)
 {
  this.name = name;
  return name;
 }
 
 public int getDogName()
 {
  return age;
 }
 
 public int setDogAge(int age)
 {
  this.age = age;
  return age;
 }
 
 public int getDogAge()
 {
  return age;
 }
 
 public int computeDogAge()
 {
  this.age = age*7;
  return age;
 }
 
 public String toString()
 {
  String dogsname= "Dog's name: ";
  String dogsage= "Dog's age: ";
  return dogsname + name + "\t" + 
                  dogsage +  age ;
 } 
 
 public static void main (String[] args)
 {
  Dog dog1 = new Dog(1,"Lucky");
  Dog dog2 = new Dog(2,"Starc");
  Dog dog3 = new Dog(5,"Lutchy");
  
  dog1.setDogAge(9);
  System.out.println(dog1);
  
  dog2.setDogName("Azzam");
  System.out.println(dog2);
  
  System.out.println(dog3);
  
  System.out.println();
  System.out.println("Dog's ages in person 
                       + years:");
  System.out.println(dog1.computeDogAge());
  System.out.println(dog2.computeDogAge());
  System.out.println(dog3.computeDogAge());
 }
}
Read More

Creating Sphere Class in Java

Problem:

Design and implement a class called Sphere that contains instance data that represents the sphere’s diameter. Define the Sphere constructor to accept and initialize the diameter, and include getter and setter methods for the diameter. Include methods that calculate and return the volume(4/3*PI*r^3) and surface area(4*PI*r^2)  of the sphere. Include a toString method that returns a one-line description of the sphere. Create a driver class called MultiSphere, whose main method instantiates and updates several Sphere objects.

Solution:

//Quick review: a class is like a complex variable

public class Sphere
{
 private int diameter;
 private double area;
 private double volume;
 

 public Sphere(int diameter)
 

  this.diameter = diameter;
  setSphereVolume();
  setSphereArea();
 }
 
 

 public void setSphereDiameter(int diameter)
 {
  this.diameter = diameter;
 }
 
 public int getSphereDiameter()
 {
  return diameter;
 }
 public void setSphereVolume()
 {

  volume = Math.PI * (4.0/3.0) * 
           Math.pow((double)diameter/2.0,3);
 }
public double getSphereVolume()
 {
  return volume;
 }
 
 public double getSphereArea()
 {
  return area;
 }
 public void setSphereArea()
 {
  area = Math.PI * 4.0 * 
          Math.pow((double) diameter/2.0,2);
 }
 
 
 public String toString()
 {
  
  String info1 = Integer.toString(diameter);
  String info2 = Double.toString(area);
  String info3 = Double.toString(volume);
  return "Diameter: " + 
    info1 + "\t" + "Area: " + info2 + "\t" +
           "Volume: " + info3 + "\t";
 }
 
 public static void main (String[] args)
 {
  
  Sphere sphere1 = new Sphere(4);
  Sphere sphere2 = new Sphere(9);
  Sphere sphere3 = new Sphere(13);
  
  //Time to play around with the methods
  sphere1.setSphereDiameter(7);
  System.out.println
               (sphere1.getSphereVolume());
  System.out.println
               (sphere1.getSphereArea());
  System.out.println
               (sphere1.getSphereDiameter());

  System.out.println(sphere1);
  System.out.println();
  
  System.out.println(sphere2.getSphereVolume());
  System.out.println(sphere2.getSphereArea());
  System.out.println(sphere2.getSphereDiameter());

  System.out.println(sphere2);
  System.out.println();
  System.out.println(sphere3.getSphereVolume());
  System.out.println(sphere3.getSphereArea());
  System.out.println(sphere3.getSphereDiameter());
  System.out.println(sphere3);

 }
}
   
Read More

Converting form Decimal to Binary in Java

Problem:

Write a program that reads a string in binary form from the user (i.e of the form "001010101") and returns the integer equivalent of the string (starting from right to left for the lest significant bit). For example, "0101" is from right to left:
(1* 2^0) + (0* 2^1) + (1* 2^2) + (2* 2^3) which is equal to 5.


Output:

Please enter the binary string:
0001 

The integer value is 1


Solution:

There are two methods to solve this problem. They are listed respectively.
import java.util.Scanner;
public class Problem2version1 
{
 
 public static void main(String[] args)
 {
  Scanner scan=new Scanner(System.in);
  
  System.out.println("Please enter the binary string:");
  String input=scan.next();
  int sum=0;
  int power2=1;
  for(int n=input.length()-1;n>=0;n--)
  {
   if(input.charAt(n)=='1')
    sum += power2;
    
   power2 *= 2;
  }
  System.out.println("The integer value is "+sum);
 }
}

import java.util.Scanner;

public class Problem2
{
 public static void main(String [] args)
 {
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter the binary string: ");
  String s = scan.next();
  int L = s.length();
  int i = 0;//iterator
      double k = 0;//the value of 1 in the string everytime
  double sum = 0;//the total sum
 
  while (i
Read More

Printing Asterisks Triangle Shapes in Java

Problem:

Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( '*' ); which causes the asterisks to print side by side. A statement of the form System.out.println(); can be used to move to the next line. A statement of the form System.out.print( ' ' ); can be used to display a space for the last two patterns. There should be no other output statements in the program. [Hint: The last two patterns require that each line begin with an appropriate number of blank spaces.]

                     


Shape (a):

public class Exercice2a

{
 public static void main (String[] args)
 {
  for (int count =0; count < 10; count++)
  {
    for (int j=0; j < count+1; j++)
       System.out.print("*");
    System.out.println();
  }
 }
}

Shape (b):

public class Exercice2b

{
 public static void main (String[] args)
 {
  for (int count =11; count >= 0; count--)
  {
    for (int j=0; j < count-1; j++)
       System.out.print("*");
    System.out.println();
  }
 }
}

Shape (c):

public class Exercice2c

{
 public static void main (String[] args)
 {
        for(int count = 0; count < 10; count++)
        {
            for(int index=1; index < count+1; index++)
                System.out.print(" ");

            for(int star=10; star > count; star--)
                System.out.print("*");
            System.out.println();
        } 
    }
}

Shape (d):

public class Exercice2d

 {
 public static void main (String[] args)
  {
        for(int count = 10; count > 0; count--)
        {
            for(int index=0; index < count-1; index++)
                System.out.print(" ");
            
            for(int star=10; star > count-1; star--)
                System.out.print("*");
            
            System.out.println();
        }
 }
Read More

Determining if Customers had exceeded their Credit Limit in Java

Problem:

Develop a Java application that will determine whether any of several department-store customers has exceeded the credit limit on a charge account. For each customer, the following facts are available:a) account numberb) balance at the beginning of the monthc) total of all items charged by the customer this monthd) total of all credits applied to the customer’s account this monthe) allowed credit limit.The program should input all these facts as integers, calculate the new balance (= beginning balance + charges – credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the program should display the message "Credit limit exceeded


Solution:

 import java.util.Scanner;

public class problemg
{
  public static void main(String[] args)
       {
        Scanner scan = new Scanner (System.in);
        {
        //Let's declare our account detail variables
        //Note: to make coding faster, you can declare variables
        //that use the same data type (e.g., int) together with
        //with a comma to separat the variables, without or without
        //initializing them (e.g., making them equal to something)
        int account = 1, balance,charges,credits,credit_limit, newbal;
        
        //Let's assume that an account number can't be zero so that 
        //we can loop over every customer account number until we
        //type in 0 to tell the program to stop
        while( account != 0 )
          {
          //Let's just add a new blank line to make things look nicer
          System.out.println();
          System.out.print("Input Account Number: ");
          account = scan.nextInt();           
          
          System.out.print("Input Beginning Balance: ");
          balance = scan.nextInt();
          
          System.out.print("Input Total Charges: ");
          charges = scan.nextInt();
          
          System.out.print("Input Total Credits: ");
          credits = scan.nextInt();
          
          System.out.print("Input Credit Limit: ");
          credit_limit = scan.nextInt();

          //And time for the calculations and displaying what the paragraph wants
          newbal = balance + charges - credits;
          System.out.println("Equivalent New Balnce: " + newbal);

               if ( newbal > credit_limit)
               {
                  System.out.println("Credit Limit Exceeded");
                break;
               }
          }
       }
}
}
Read More

Printing the reverse of an Integer in Java

Problem:

Write a program that reads an integer N followed by N positive integers. For each entered integer, your program prints (on a new line) its digits in reverse.


Output:

3
35423
7
98710789
3
32453

7
98701789


Solution:

 import java.util.Scanner;
 
 public class lauprob6
 
 {
  public static void main (String[] args)
  
  {
   Scanner scan = new Scanner (System.in);
   
   int x= 1;
   
   while (x == 1)
    
   {
    
   int digit = scan.nextInt();
   
   String str = Integer.toString(digit);
   
   for (int count = str.length() - 1; count >=0;count--)
    
   System.out.print(str.charAt(count));
   System.out.println();
   
   }
  }
 }
Read More

Counting the Number of Primes Entered in Java

Problem:

Write a program that reads positive integers from the keyboard until the user enters 0. Then the program prints the number of prime numbers entered.

Output:

Enter prime numbers seperated by space(0 to quit):
2 3 5 03


Solution:

import java.util.Scanner;

public class lauprob5

{
 public static void main(String[] args) 
 
 {
  Scanner scan = new Scanner (System.in);
  
     //We need something to use to get into the loop
     int prime = 1, count = 0;
     
     System.out.println("Enter prime numbers seperated by space(0 to quit):");
     
     //We'll keep on looping and scanning till we scan a 0
     while (prime != 0)
      
     {
      
     prime = scan.nextInt();
     
     //It's easier to prove that a number that we think is prime
     // isn't really prime because a prime is a number that's
     //only divisible by one and itself
     //so we'll make our initial boolean: 
     boolean isPrime = true; 
     
     //there are no prime numbers less than 2 so we need this
     //to quickly prove that a number isn't prime, so how easy
     //to prove that a number isn't prime?
     if (prime < 2) isPrime = false; 
     
     for (long i = 2; i*i <= prime; i++)
      
     { 
      //if the prime is divisble by i, which a number
      //that is neither 1 or the entered number, then 
      //the number is NOT prime and the case is closed (break)
       if (prime % i == 0) 
       
       isPrime = false; 
      break; 
     } 
     
     //If after existing that loop, we never found 
     //any divisors of the number (and it's not less than true
     //then it is of course a prime number so we should
     //increase our variable that counts the number of scanned
     //prime numbers by one
     if (isPrime) 
      
      count ++;
     }
     System.out.print(count);
     } 
 }
Read More

Removing the Duplicates of a String in Java

Problem:

Write a program that read a string str and prints a string obtained from str by removing/ignoring duplicates. For example, if str is abbacdcae, then your program prints abcde. In other words, only the first occurrence of a character is printed.


Solution:

          import java.util.Scanner;

public class lauprob3
{
 public static void main(String[] args) 
 {
  //First off, let's scan our string
   Scanner scan = new Scanner (System.in);
  
     String string = scan.nextLine();
     
     //We're gonna be looping over each character in the String
    for (int x = 0; x < string.length(); x++)
      
         //We're gonna loop over every character of the String
         //that comes after the character from the outer/first loop
         for (int y = x+1; y <= string.length()-1; y++)
         {
             //We're gonna check if any of the characters after x
             //ie the characters from this second loop, are the same as 
             //as x so that we'll remove x's duplicates
             if (string.charAt(x) == string.charAt(y))
             {
                 //If we find that x and y are equal 
                 //then we're going to make our string equal to
                 //itself but without the y character through using
                 //substrings that pass over y
                 //Note: substring(a,b) means from a to b but only including a
                 string = string.substring(0,y)+ string.substring(y+1,string.length());          
                 
                 //We need to get rid of an extra increment because we
                 //deleted a repeated character
                 y--;
             }
         }
     
     System.out.println(string);
 }
}
Read More

Checking whether a Number is a Power of 2 in Java

Problem:

Write a program that reads an integer n and checks whether n is a power of 2 (powers of 2 are 1,2,4,8,16,32, …). The output of your program is either “yes” or “no”.


Solution:

 import java.util.Scanner;

public class lauprob4
{
 public static void main (String[] args)
 
 {
  
  //Simple scanning of the number
  Scanner scan = new Scanner (System.in);
  
  System.out.print ("Enter an integer: ");
  
  int n = scan.nextInt();
  
  //Of course, a number is a power of n if its 
  //only divisors are 2 and 1, i.e. n=2^x * 1=2*2*2*2*...*1
  //this will make us exit the loop the second we find
  // out that the number isn't (still) divisible by 2
  //such as 8 which is a power of 2 and will eventually be
  //equal to one since with this loop 8 becomes 4, 2, then 1
  //Conversely, if it's not a power of two then we'll come out anyway
  // such as 6 becomes 3 which isn't divisible by 2 and so we exist
  //In any case we're gonna exit the loop eventually
  while (n % 2 == 0)
  { 
  //We just keep on dividing the number by 2 till we get out
  till we n /= 2;
  }
  //If our number really is a power of 2
  //then we'll eventually have to reach 1
  //for example, 16 becomes 8 which becomes 4 
  //which becomes 2 which becomes 1
  if (n == 1)
   
   System.out.println(n + " is a power of two");
  
  //if the number isn't a power of two, then the loop
  //would've changed the number to a number that isn't one
  else 
  
   System.out.println(n + " is not a power of two"); 
  
 }
}
Read More

Checking if Your Name is in a String in Java

Problem:

Write a program that keeps reading strings until it reads the string “xyz”. If your first name is among the entered strings, the program prints “My name is there.” Otherwise, it prints “My name is not listed. Please add it.”


Solution:

mport java.util.Scanner;
 
public class lauprob1

{
 public static void main (String[] args)
 
 {
  Scanner scan = new Scanner (System.in);
  
  //We made the String equal to null because we just
  //need a default initial value for it first to be 
  //able to play with the String later
  String str = null;
  
  //And we played with it now :P
  str = scan.nextLine();
  
  //We will now loop over the word that is entered
  //through the Scanner until we scan xyz and stop
   while (!(str.equals("xyz")))
   
  {
   //We will check if the entered String is my name
   if ( str.equalsIgnoreCase("George")) 
   {
    //Since my name is present, then I'll print this
    //and then scan the next entered String
    System.out.println("My name is there.");
    
    str = scan.nextLine(); 
   }
   
   else 
    
   {
    //If my name isn't there, then I'll just print this
    //and scan the next word so that loop will continue
    //and continue till we type xyz and end the program
    System.out.println("My name is not listed. Please add it");
    str = scan.nextLine(); 
   }
  } 
 }
}
Read More

Checking Weather Your Name is Listed or Not in Java

Problem:

Write a program that reads an integer N followed by N lists of strings. Each list ends with the string “xyz”. If your first name appears in list K (1 <= K <= N), and K is the smallest such value, then your program prints “My name is in list K!” Otherwise, it prints “My name is not listed. Please add it somewhere.”


Output:

3
Mike
Gregory
Henning
John
xyz
George
Faisal
xyz
Mathew
Faisal
Rolf
xyz

My name is in list 2


Solution:

import java.util.Scanner;
 
public class lauprob2
{
 public static void main (String[] args)
 
 {
  Scanner scan = new Scanner(System.in);
  
  String str = "e";
  
  int input = scan.nextInt();
  
  /*We're making an array of n integers,
   with n being the number of lists we're going
   to read from the screen*/
   int[] name_appearance = new int[input];
  //Note: the value of all 3 integer variables of this array is zero by default 

  //We're going to loop over each entered list to keep track
  //of where my name is appearing
  for (int count = 0; count < input; count++)
   
  {
   //We just need a random initial value for the String variable that we
   //will be using to check the scanned string 
   str = "e";
   
   //In this inner loop, we're going to loop over each scanned string
   //from the same list to check if my name is there.
   //Note: the condition will stop the loop when we reach our end marker=xyz
   for (int index = 0; !(str.equals("xyz"));index++)
    
   {
    str = scan.nextLine();
    
    //If we found out that my name is equal to the entered String
   //in list number n, we're going to make
    if (str.equalsIgnoreCase("george") && index < input)
     
     //In this step, we're going to make the array element (list number) that
    //has my name be equal to well, the actual list number
    name_appearance[count] = count+1;
    
    //for example, if the second list has my name, then what we're really doing here
    //is having count=1 and making name_appearance[1]=1+1=2
    //If the name was at the first list (i.e., at our first try without increasing count)
    //then the variables would be count=0 and name_apperance[0]=1
 
   }
   
  }
  
  //We're going to go through each array element to check which element has a value
  //other than zero; this is because we changed the array element value of the list that
  //has my name in the loops above. Kinna sounds complicated and weird, but this is     
  // just one way of solving this problem so don't get freaked out over not
  // wanting to ever do this code again :P
  
  for (int NameList : name_appearance)
   
   if (NameList != 0)
    
    System.out.println("My name is in list" + NameList);
  
 }
 
}
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