Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java practice #6

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions ch03/CelsiusToFahrenheit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.Scanner;

public class CelsiusToFahrenheit {

public static void main(String[] args) {
// Create variables
double celsius;
double fahrenheit;
final int FREEZING_TEMP = 32;
Scanner input = new Scanner(System.in);

// Ask for number in celsius, then save that input as the celsius variable
System.out.print("Enter a temperature in Celsius: ");
celsius = input.nextDouble();
System.out.printf("%.1f celsius\n", celsius);

// Conver celsius to fahrenheit
fahrenheit = (celsius * 9.0/5.0) + (FREEZING_TEMP);

// Display result!
System.out.printf("%.1f celsius = %.1f fahrenheit\n", celsius, fahrenheit);



}


}
45 changes: 35 additions & 10 deletions ch03/Convert.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,41 @@ public static void main(String[] args) {
final int IN_PER_FOOT = 12;
Scanner in = new Scanner(System.in);

// prompt the user and get the value
System.out.print("Exactly how many cm? ");
cm = in.nextDouble();

// convert and output the result
inches = (int) (cm / CM_PER_INCH);
feet = inches / IN_PER_FOOT;
remainder = inches % IN_PER_FOOT;
System.out.printf("%.2f cm = %d ft, %d in\n",
cm, feet, remainder);
System.out.print("Enter 1 to convert centimeters to feet and inches\n"
+ "Enter 2 to convert feet and inches to centimeters\n"
+ "Your choice: ");

int choice = in.nextInt();

if (choice == 1) {
System.out.print("Exactly how many cm? ");
cm = in.nextDouble();

if (cm < 0) {
System.out.print("Please enter a positive value for centimeters.");
} else {
inches = (int) (cm / CM_PER_INCH);
feet = inches / IN_PER_FOOT;
remainder = inches % IN_PER_FOOT;
inches = inches - (feet * IN_PER_FOOT);
System.out.printf("%.2f cm = %d ft, %d in\n", cm, feet, inches);
}
} else if (choice == 2) {
System.out.print("Enter feet: ");
feet = in.nextInt();
System.out.print("Enter inches: ");
inches = in.nextInt();

if (feet < 0 || inches < 0 || inches >= IN_PER_FOOT) {
System.out.println("Please enter valid and positive values for feet and inches.");
} else {
cm = (feet * IN_PER_FOOT + inches) * CM_PER_INCH;
System.out.printf("%d ft, %d in = %.2f cm\n", feet, inches, cm);
}
} else {
System.out.println("Invalid choice, please enter 1 or 2.");
}

}

}
6 changes: 5 additions & 1 deletion ch03/Echo.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ public static void main(String[] args) {

System.out.print("Type something else: ");
line = in.nextLine();
System.out.println("You also said: " + line);
System.out.println("You then said: " + line);

System.out.print("One more time please: ");
line = in.nextLine();
System.out.println("I totally agree with " + line);
}

}
5 changes: 3 additions & 2 deletions ch03/Formatting.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static void main(String[] args) {
// formatting output

System.out.print(4.0 / 3.0);
System.out.printf("Four thirds = %.3f", 4.0 / 3.0);
System.out.printf("Four thirds = %.3f\n", 4.0 / 3.0);

int inch = 100;
double cm = inch * CM_PER_INCH;
Expand All @@ -27,7 +27,8 @@ public static void main(String[] args) {
inch = (int) (cm / CM_PER_INCH);
System.out.printf("%f cm = %d in\n", cm, inch);

System.out.printf("inches = %d" + inch); // error

System.out.printf("inches = %d", inch); // Error was a '+' sign where a comma should have been, fixed!
}

}
43 changes: 43 additions & 0 deletions ch03/GuessGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.util.Random;
import java.util.Scanner;

/**
* "Guess My Number" game with added fun features.
*/
public class GuessGame {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();

System.out.println("Welcome to the Guess My Number game!");
System.out.println("I've picked a number between 1 and 100.");
System.out.println("Try to guess it!");

int numberToGuess = random.nextInt(100) + 1;
int attempts = 0;
int maxAttempts = 15;

while (attempts < maxAttempts) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
attempts++;

if (guess == numberToGuess) {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts!");
break;
} else if (guess < numberToGuess) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
}

if (attempts == maxAttempts) {
System.out.println("Oops! You've reached the maximum number of attempts.");
System.out.println("The correct number was: " + numberToGuess);
}

scanner.close();
}
}
3 changes: 2 additions & 1 deletion ch03/ScannerBug.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ public static void main(String[] args) {
name = in.nextLine();
System.out.print("What is your age? ");
age = in.nextInt();
in.nextLine(); // Consume the newline character after reading the age.
System.out.printf("Hello %s, age %d\n", name, age);

in.reset();
System.out.println();

System.out.print("What is your age? ");
age = in.nextInt();
in.nextLine(); // Consume the newline character after reading the age.
System.out.print("What is your name? ");
name = in.nextLine();
System.out.printf("Hello %s, age %d\n", name, age);
Expand Down
27 changes: 27 additions & 0 deletions ch04/Date.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

public class Date {

public static void printAmerican(int date, int year, String day, String month) {
System.out.print("American format for date: ");
System.out.print(day);
System.out.print(", ");
System.out.print(month);
System.out.print(" ");
System.out.print(date);
System.out.print(", ");
System.out.println(year);


}

public static void main (String[] args) {
int date = 11;
int year = 1993;
String day = "Monday";
String month = "April";
printAmerican(date, year, day, month);

}

}

61 changes: 61 additions & 0 deletions ch04/IsPalindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import java.util.Random;

public class IsPalindrome {
public static void main(String[] args) {
Random random = new Random();
String input = generateRandomString(random, 6);
boolean isPalindrome = isSpecial(input);
int longestPalindromeLength = getPalindromeLength(input);
System.out.println("Random String: " + input);
System.out.println("Is it a palindrome? " + isPalindrome);
System.out.println("Longest Palindromic Length: " + longestPalindromeLength);
}

public static boolean isSpecial(String text) {
String tempText = alterText(text);
return text.equals(tempText);
}

public static String alterText(String inputText) {
if (inputText == null || inputText.isEmpty()) {
return inputText;
}
return inputText.charAt(inputText.length() - 1) +
alterText(inputText.substring(0, inputText.length() - 1));
}

public static String generateRandomString(Random random, int length) {
String chars = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(chars.length());
sb.append(chars.charAt(randomIndex));
}
return sb.toString();
}

public static int getPalindromeLength(String text) {
String reversed = new StringBuilder(text).reverse().toString();
int maxLength = 0;
int currentLength = 0;

for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reversed.charAt(i)) {
currentLength++;
if (currentLength > maxLength) {
maxLength = currentLength;
}
} else {
currentLength = 0;
}
}
return maxLength;
}



}




36 changes: 36 additions & 0 deletions ch04/Merge.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
public class Merge {
public static void main(String[] args) {

// Test cases
int[] arr1 = { 1, 3, 5 };
int[] arr2 = { 2, 4, 6, 8 };

// Call the merge function to combine the two arrays
int[] mergedArray = merge(arr1, arr2);

// Display the merged array
System.out.println("Merged Array:");
for (int num : mergedArray) {
System.out.print(num + " ");
}
}

public static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
// Place elements from array 'a' at even indices in the result array
result[2 * i] = a[i];

// Check if there's a corresponding element in array 'b' to place at odd index
if (i < b.length) {
result[2 * i + 1] = b[i];
}
}
// If array b is longer than array a, add the remaining elements of b
for (int i = a.length; i < b.length; i++) {
result[2 * i] = b[i];
}
return result;
}
}