jsquared21 / intro-to-java-programming Goto Github PK
View Code? Open in Web Editor NEWSolutions to Programming Exercises in Introduction to Java Programming, Comprehensive Version (10th Edition) by Y. Daniel Liang
License: MIT License
Solutions to Programming Exercises in Introduction to Java Programming, Comprehensive Version (10th Edition) by Y. Daniel Liang
License: MIT License
I think you should use System.out.print("The ISBN-10 number is " + d1 + d2 + d3 + d4 + d5+ d6 + d7 + d8 + d9);
count is 1/4 of the real count assuming the last card of each interval of 4 draws is the unpicked suit every time.
crude fix: https://pastebin.com/4BLudqbd
package exc_15_21;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Exc_15_21 extends Application {
Pane pane = new Pane();
Circle circle = new Circle(200,200,100);
Circle outerCircle = new Circle(200,200,112);
Circle innerCircle = new Circle(200,200,88);
@Override
public void start(Stage primaryStage){
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);
pane.getChildren().add(circle);
double angle1 = Math.toRadians(Math.random()*360);
double x1 = circle.getCenterX() + (circle.getRadius()*Math.cos(angle1));
double y1 = circle.getCenterY() - (circle.getRadius()*Math.sin(angle1));
double angle2 = Math.toRadians(Math.random()*360);
double x2 = circle.getCenterX() + (circle.getRadius()*Math.cos(angle2));
double y2 = circle.getCenterY() - (circle.getRadius()*Math.sin(angle2));
double angle3 = Math.toRadians(Math.random()*360);
double x3 = circle.getCenterX() + (circle.getRadius()*Math.cos(angle3));
double y3 = circle.getCenterY() - (circle.getRadius()*Math.sin(angle3));
ArrayList<Circle> circles = new ArrayList<>();
Circle c1 = new Circle(x1,y1,12);
Circle c2 = new Circle(x2,y2,12);
Circle c3 = new Circle(x3,y3,12);
circles.add(c1);
circles.add(c2);
circles.add(c3);
display(circles);
pane.setOnMouseDragged(e -> {
for(int i=0 ; i< circles.size(); i++)
{
if(circles.get(i).contains(e.getX(),e.getY()))
{
if( outerCircle.contains(e.getX(),e.getY()) && !innerCircle.contains(e.getX(),e.getY()) )
{
double[] pointsOnCircle = getPoints(e.getX(),e.getY());
circles.get(i).setCenterX(pointsOnCircle[0]);
circles.get(i).setCenterY(pointsOnCircle[1]);
display(circles);
}
}
}
});
primaryStage.setScene(new Scene(pane,400,400));
primaryStage.setTitle("Exc_15_21");
primaryStage.show();
}
public double[] getPoints( double x, double y)
{
double angle = (Math.atan((y-circle.getCenterY())/(x-circle.getCenterX())));
angle *= -1;
if(circle.getCenterX()>x)
{
angle +=Math.PI;
}
return new double[]{circle.getCenterX() + (circle.getRadius() * Math.cos(angle)) , circle.getCenterY() - (circle.getRadius() * Math.sin(angle))};
}
public ArrayList<Double> getSides(ArrayList<Circle> p)
{
ArrayList<Double> sides = new ArrayList<>();
sides.add(Math.sqrt(Math.pow(p.get(0).getCenterX() - p.get(1).getCenterX(), 2) + Math.pow(p.get(0).getCenterY() - p.get(1).getCenterY(), 2)));
sides.add(Math.sqrt(Math.pow(p.get(1).getCenterX() - p.get(2).getCenterX(), 2) + Math.pow(p.get(1).getCenterY() - p.get(2).getCenterY(), 2)));
sides.add(Math.sqrt(Math.pow(p.get(2).getCenterX() - p.get(0).getCenterX(), 2) + Math.pow(p.get(2).getCenterY() - p.get(0).getCenterY(), 2)));
return sides;
}
public ArrayList<Double> getAngles(ArrayList<Double> sides)
{
ArrayList<Double> angles = new ArrayList<>();
angles.add(Math.toDegrees(Math.acos((sides.get(0) * sides.get(0) - sides.get(1) * sides.get(1) - sides.get(2) * sides.get(2)) / (-2 * sides.get(1) * sides.get(2)))));
angles.add(Math.toDegrees(Math.acos((sides.get(1) * sides.get(1) - sides.get(0) * sides.get(0) - sides.get(2) * sides.get(2)) / (-2 * sides.get(0) * sides.get(2)))));
angles.add(Math.toDegrees(Math.acos((sides.get(2) * sides.get(2) - sides.get(1) * sides.get(1) - sides.get(0) * sides.get(0)) / (-2 * sides.get(0) * sides.get(1)))));
return angles;
}
public void display(ArrayList<Circle> circles)
{
pane.getChildren().clear();
pane.getChildren().add(circle);
Polygon triangle = new Polygon();
ObservableList<Double> points = triangle.getPoints();
for(int i=0 ; i<circles.size(); i++)
{
points.add(circles.get(i).getCenterX());
points.add(circles.get(i).getCenterY());
}
triangle.setStroke(Color.BLACK);
triangle.setFill(Color.WHITE);
pane.getChildren().add(triangle);
ArrayList<Double> angles = getAngles(getSides(circles));
for(int i=0 ; i<circles.size(); i++)
{
pane.getChildren().add(circles.get(i));
pane.getChildren().add(new Text( circles.get(i).getCenterX()+5 , circles.get(i).getCenterY()-18 , String.format("%.2f", angles.get(i))));
}
}
}
Hey man,
I could not find your answer to Programming Exercise Chapter. 6 Number 34. so I thought I could share my answer :).
PS: Don't know it's efficient, or even a good implementation, but it works pretty good, for any given year.
PS2: I could not find the answer to question No. 33 too, and unfortunately I couldn't solve it yet, though I am working hard on it. When I have written the answer, I will share the code. :)
import java.util.Scanner;
/**
* Created by SquirrelCoder on 29-Jan-17.
*/
public class ZellerAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// getting user input
System.out.print("Enter full year (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter month as number between 1 and 12: ");
int month = input.nextInt();
// check user input
if (!checkMonth(month)) {
System.exit(0);
}
// print the calendar header
printCalendarHeader(month, year);
// print the calendar first day
printFirstDay(month, year);
// print the calendar itself
printCalendarItself(month, year);
}
public static int weekDay(int day, int month, int year) {
if (month == 1 || month == 2) {
month = month + 12;
year--;
}
int q, m, k, j, h;
q = day;
m = month;
k = year % 100;
j = (int) (year / 100.0);
h = (q + (int) ((13 * (m + 1)) / 5.0) + k + (int) (k / 4.0) + (int) (j / 4.0) + (5 * j)) % 7;
return h;
}
public static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
public static void printCalendarHeader(int month, int year) {
switch (month) {
case 1:
System.out.print("\t\tJanuary\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 2:
System.out.print("\t\tFebruary\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 3:
System.out.print("\t\tMarch\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 4:
System.out.print("\t\tApril\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 5:
System.out.print("\t\tMay\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 6:
System.out.print("\t\tJune\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 7:
System.out.print("\t\tJuly\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 8:
System.out.print("\t\tAugust\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 9:
System.out.print("\t\tSeptember\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 10:
System.out.print("\t\tOctober\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 11:
System.out.print("\t\tNovember\t");
System.out.println(year);
System.out.println("---------------------------");
break;
case 12:
System.out.print("\t\tDecember\t");
System.out.println(year);
System.out.println("---------------------------");
break;
}
System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat");
}
public static int lastDayOfMonth(int month, int year) {
int lastDayOfMonth;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
lastDayOfMonth = 31;
} else if (month == 2) {
if (isLeapYear(year)) {
lastDayOfMonth = 29;
} else {
lastDayOfMonth = 28;
}
} else {
lastDayOfMonth = 30;
}
return lastDayOfMonth;
}
public static boolean checkMonth(int month) {
if (month > 12 || month < 0) {
System.out.println("Invalid Month!");
return false;
}
return true;
}
public static void printFirstDay(int month, int year) {
int firstDay = weekDay(1, month, year);
switch (firstDay) {
case 0:
System.out.print("\t\t\t\t\t\t1");
break;
case 1:
System.out.print("1");
break;
case 2:
System.out.print("\t1");
break;
case 3:
System.out.print("\t\t1");
break;
case 4:
System.out.print("\t\t\t1");
break;
case 5:
System.out.print("\t\t\t\t1");
break;
case 6:
System.out.print("\t\t\t\t\t1");
break;
}
System.out.print("\t");
}
public static void printCalendarItself(int month, int year) {
// find out the last day of that month
// whether it's 28/29/30/31 days
int lastDayOfMonth = lastDayOfMonth(month, year);
// print the calendar itself
for (int i = 2; i <= lastDayOfMonth; i++) {
int printedDay = weekDay(i, month, year);
if (printedDay == 1) {
System.out.println();
}
System.out.print(i + "\t");
}
}
}
Hi, how are you? I have been looking at your code since around last November in 2016, and I would like to upload some of my own exercises which have been derived from a variety of your programs. The format would look similar to code academy and hacker rank. However, individuals would copy and paste the code that I upload, and fill in the blanks missing in the program in order to get it to work. Each uploaded code would basically function like a tutorial.
However, I have noticed that you do not have a license. This means that I am unable to use anything that has been derived from your code. I am writing to you hoping that you respond and that you allow me to upload code onto github that has been derived from your programs.
Thank you for your time.
Course course1 = new Course("Data Structure");
course1.addStudent("Peter Jones");
course1.addStudent("Kim Smith");
course1.addStudent("Anne Kennedy");
course1.addStudent("Steve Boss");
System.out.println("Nmuber of students in course1: " + course1.getNumberOfStudents());
String[] students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++) {
System.out.print(students[i] + ", ");
}
System.out.println();
course1.dropStudent("Peter Jones");
for (int i = 0; i < course1.getNumberOfStudents(); i++) {
System.out.print(students[i] + ", ");
}
dropstudent always remove last element not specified student. what is solve this bug?
please don't use this library import org.apache.commons.lang3.ArrayUtils;
Hi,
I tested this program, and I think something is wrong:
if I try to convert to following expression: 2 * (1 * 2 + 3), I will get 2 1 2 3 + * , instead of 2123+*.
I made a different solution with one stack for the operators and parentheses with the help of the conversion rules on this link:
http://csis.pace.edu/~wolf/CS122/infix-postfix.htm
The instructions say: “Implement the method in a way that takes at most list1.length + list2.length comparisons”, but your sort takes many more than that.
Count the number of comparisons in the sort
public static void sort(int[] list) {
int nCompare = 0;
for (int i = 0; i < list.length - 1; i++) {
int min = list[i];
int minIndex = i;
for (int j = i + 1; j < list.length; j++) {
nCompare++;
if (list[j] < min) {
min = list[j];
minIndex = j;
}
}
if (minIndex != i) {
list[minIndex] = list[i];
list[i] = min;
}
}
System.out.println("Total compares: " + nCompare);
}
}
For arrays [10, 20, 30, 40, 50] and [1, 2, 3, 4, 5] in that order, it takes 45 comparisons, which is far more than the 10 that the exercise allows.
(By the way, several students in my class copied this wrong solution and lost a large number of points for doing it incorrectly -- and for plagiarism.)
Your code on 22.3 doesn't solve. An example of a failure is an s1 of "cocork" and an s2 of "cork". i would reach 3 by the time it realizes that co is not a proper substring. I don't know a solution.
The question ask to display the number of leap years found along with the years. Where in the program it only shows the years not the count.
System.out.print(year + (count % 10 == 0 ? "\n" : " "));
The code didn't work.
Hi,
One criterion is missing before the 68th row, at the while loop premise. Instead of
while (!operatorStack.isEmpty() && (operatorStack.peek() == '*' || operatorStack.peek() == '/' || operatorStack.peek() == '%' )) { processAnOperator(operandStack, operatorStack); }
the correct version would be:
while(!operatorStack.isEmpty() && (operatorStack.peek() == '*' || operatorStack.peek() == '/' || operatorStack.peek() == '^' || operatorStack.peek() == '%')) { processAnOperator(operandStack, operatorStack); }
Without this criterion (operatorStack.peek() == '^' ||) the following expression gives wrong result:
(5 * 2 ^ 3 * 2 + 2 * 3 % 2) * 4 is correctly 320, but without this criterion it is 1280, because 2 ^ 3 * 2 is evaluated as 2 ^ 6.
Hi,
I think this statement is wrong: side1 + side2 > side3 || side1 + side3 > side2 || side2 + side3 > side1;
for example take the sides as follow: side1 == 5, side2 == 21 and side3 == 6, there is no way to compute this value, even though the boolean isValid
method, evaluates to true
, which should evaluates to false
!
I think this is the right statement: side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1;
btw, this method could be written as follow too:
public static boolean isValid(double side1, double side2, double side3) {
return side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3;
}
Hi,
How are you Sir?
So there is a problem in Exercise_09_05 , because you have accessed a Static Field using an instance reference
System.out.println(calender.get(calender.MONTH) + "/" +
calender.get(calender.DAY_OF_MONTH) + "/" + calender.get(calender.YEAR));
The correct way to access a static field, would be through the class name, like the following:
Instantiate a new object:
GregorianCalendar calendar = new GregorianCalendar();
and then access the static field using the GregorianCalendar
class itself.
System.out.println(calendar.get(GregorianCalendar.MONTH) + "/" +
calendar.get(GregorianCalendar.DAY_OF_MONTH) +
"/" + calendar.get(GregorianCalendar.YEAR));
Thanks a lot.
The question requires answer for pi when i=10000 to i=100000, but the programme only calculate i=10000, to=20000 and i=100000
Hi!
I found some bug in StopWatch class's run method (Exercise_16_20). The code is:
protected void run() {
if (minute == 59)
hour = hour + 1;
if (second == 59)
minute = minute + 1;
second = second < 59 ? second + 1 : 0;
text.setText(getTime());
}
This code segment will be invoked every second. It means for example, if the minute variable reaches 59, then every second the hour will be incremented (so in 10 second 10 times). The minute variable can be higher than 59, it is also unusual. It can be tested, if you set the Duration.millis to a low value, f.e. to 10ms. I think the code below could work better:
protected void run() {
if(min == 59 && sec == 59) {
hour++;
min = 0;
sec = 0;
}
if(sec == 59 && min != 59) {
min++;
}
sec = (sec < 59 ? sec + 1 : 0);
text.setText(getTime());
}
The same problem is with the method moveClock() in Exercise_15_32 in ClockPane class. It could be modified similarly.
Bye,
Csaba
I am not sure if it is an issue with the Java version I am coding on, an Eclipse issue or code issue. When I run the code in Exercise_1_7, it outputs 4.0 as both outputs. I have to change all instances of 1 to 1.0 in the fractions, like this:
`public class Exercise_1_7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(4 * ( 1.0 - (1.0 / 3) + (1.0 / 5) - (1.0 / 7) + (1.0 / 9) - (1.0 / 11)));
System.out.println(4 * ( 1.0 - (1.0 / 3) + (1.0 / 5) - (1.0 / 7) + (1.0 / 9) - (1.0 / 11) + (1.0 / 13)));
}
}`
My output is:
2.9760461760461765
3.2837384837384844
Only one condition is satisfied. else part is incomplete. Link to question
Hey man,
I could not find your answer to Question No. 34 Chapter 5.
This is my answer, though I am not sure, if it's efficient or not. (Still learning :D)
If you like, you may add it to the answers :).
public static void main(String[] args) {
// Scissor (0)
// Rock (1)
// Paper (2)
Scanner input = new Scanner(System.in);
int computerItem;
int numOfComputerWon = 0;
int numOfHumanWon = 0;
while (true) {
System.out.print("Number of Your Points: " + numOfHumanWon);
System.out.print("\nNumber of Computer Points: " + numOfComputerWon);
System.out.println();
System.out.println();
System.out.print("The Computer is: ");
computerItem = (int) (Math.random() * 3);
switch (computerItem) {
case 0:
System.out.print("Scissor");
break;
case 1:
System.out.print("Rock");
break;
case 2:
System.out.print("Paper");
break;
}
System.out.println();
System.out.print("Scissor (0), Rock (1), Paper (2): ");
int humanItem = input.nextInt();
System.out.print("You are ");
switch (humanItem) {
case 0:
System.out.print("Scissor");
break;
case 1:
System.out.print("Rock");
break;
case 2:
System.out.print("Paper");
break;
}
System.out.println();
if (humanItem == 0 && computerItem == 2) {
numOfHumanWon++;
System.out.print("You Won! 1 Point for You!");
} else if (humanItem == 2 && computerItem == 0) {
numOfComputerWon++;
System.out.print("You Lost! 1 Point for Computer!");
} else if (humanItem == 1 && computerItem == 0) {
numOfHumanWon++;
System.out.print("You Won! 1 Point for You!");
} else if (humanItem == 0 && computerItem == 1) {
numOfComputerWon++;
System.out.print("You Lost. 1 Point for Computer!");
} else if (humanItem == 2 && computerItem == 1) {
numOfComputerWon++;
numOfHumanWon++;
System.out.print("You Won! 1 Point for You!");
} else if (humanItem == 1 && computerItem == 2) {
numOfComputerWon++;
System.out.print("You Lost! 1 Point for Computer!");
} else {
System.out.print("Draw! Again.");
}
System.out.println();
if (numOfComputerWon - numOfHumanWon >= 2) {
System.out.print("Computer has " + (numOfComputerWon - numOfHumanWon) + " Points more than you.");
System.out.print("\nYou Lost. Maybe Next Time!");
break;
}
}
}
In Exercise_09_04 it displays the first 50 random integers between 0 and 1000, but the statement says to display the first 50 random integers between 0 and 100.
Shall I make a pull request correcting this?
Hi!
I found a mistake in method removeDuplicates. Inside the for loops there is an if branch. This contains the following:
list.remove(j);
It is wrong, because if you have the same items several times one after another, it will erase only the first one, but not the 2nd, because as you delete the first, the loop will increase value of j, and the 2nd one will not deleted. If you try it with a sample list like this: Chicago, Miami, Chicago, Chicago, Washington, the result will be: Chicago, Miami, Chicago, Washington.
You can correct it, if you decrease 'j' every time you delete an item from the list:
list.remove(j--);
Bye,
Csaba
There should be two different sums, if not the the final sum will be added to the first sum and thus wrong output.
I have a problem at 11_13,
if there are three continuous 4, the output list will have two 4s.
I think, for example, j is 5 now. After removing num1 of 5th, the num2 of 6th will move to 5th. Then j++. It leads to that num2 was passed. In other words, the for loop skiped some elements.
Change it toif(...){..} else{ j++;}
may be worked. It will j++ only if if-condition is false.
The solution for Q_04_25 is incorrect. The code gives wrong output for:
first City = Chicago
second City = Los Angeles
third City = Atlanta
Correct Logic:
if ( first.compareTo(second) > 0) {
temp = first;
first = second;
second = temp;
}
if( first.compareTo(third) > 0) {
temp = first;
first = third;
third = temp;
}
if( second.compareTo(third) > 0 ) {
temp = second;
second = third;
third = temp;
}
Before calling nextInt(), is it necessary to check boolean hasInput = scanner.hasNext();?
The problem asks for the edges (lengths of the sides) of the triangle, not the vertex points.
If you enter points (1, 1), (2, 2), and (3, 3), your program will say that it is a valid triangle -- but these points describe a straight line, not a triangle.
By the way, several students in my class copied this wrong solution and lost a large number of points for doing it incorrectly -- and for plagiarism.
YOU ARE WRONG! For you I got scolded from my GF, 1.10 you have wrong answer. See the real solution https://www.cscprogrammingtutorials.com/2015/11/program-to-calculate-average-speed-in-miles.html
Hi,
so I was working on this exercise, after I wrote it, I checked with your code, and I think it's a little bit complicated, I searched for GCD, and apparently Euclidean algorithm works much better and is faster too.
So I thought, I should implement it.
Here is my code, if you like, you can add my solution this solution (:D) as an alternative solution too :).
Thanks a lot.
public class Num_14_Euclid_Algo {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] userNumbers = new int[5];
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt();
}
System.out.println("GCD is: " + gcdOfMultipleNumbers(userNumbers));
}
public static int euclidAlgorithm(int a, int b) {
int remainder = a % b;
int quotient = 0;
while (remainder != 0) {
a = b;
b = remainder;
remainder = a % b;
quotient = b;
}
return quotient;
}
public static int gcdOfMultipleNumbers(int... array) {
int gcd = array[0];
for (int i = 1; i < array.length; i++) {
gcd = euclidAlgorithm(gcd, array[i]);
}
return gcd;
}
}
the [if statement] to judge if the input is a hex number seems wrong. "11" will be decided to be a non-hex number.
here is my if statement just for your reference:
if ((hexChar-'0'<0||hexChar-'9'>0)&&(hexChar-'A'<0||hexChar-'F'>0)) throw new NumberFormatException (
"Not a hex number!");
Hi,
I have found a little mistake in Exercise_16_08. The method isIntersect() examines wether the two circles intersect or not. This method gives true also in case of one containing the other. The method can correct like this:
public boolean isIntersect() {
double distance = Math.sqrt(Math.pow(c1.getCenterX() - c2.getCenterX(), 2) +
Math.pow(c1.getCenterY() - c2.getCenterY(), 2));
return distance < c1.getRadius() + c2.getRadius() &&
distance > Math.max(c1.getRadius(), c2.getRadius()) - Math.min(c1.getRadius(), c2.getRadius());
}
Bye,
Csaba
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.