Saturday, May 20, 2023

Exploring the Possibilities: Coding in Java with ChatGPT

Exploring the Possibilities: Coding in Java with ChatGPT

Introduction:

In today's digital age, programming has become an integral part of various domains, ranging from work-related tasks to personal projects. The use of new and advanced AI language models, such as ChatGPT4, has revolutionized the way we approach coding. In this essay, we will explore how ChatGPT can be utilized as a prompt to generate unique Java code, discussing its applications in work, personal use, and the potential for enhancing programming skills.

Promoting Unique Java Code with ChatGPT:

ChatGPT provides an excellent platform for generating unique Java code snippets, enabling users to overcome coding challenges and enhance their productivity. By providing specific prompts to ChatGPT, users can receive personalized code snippets that address their requirements. For instance, if a user requires a Java program to sort an array in ascending order, they can prompt ChatGPT with the request, and it will generate a tailored code snippet to fulfill that task. The ability to quickly obtain unique Java code through ChatGPT offers a valuable resource for developers.

Example 1: Sorting an Array in Ascending Order

public class ArraySorter {
    public static void main(String[] args) {
        int[] array = {5, 2, 8, 1, 9};
        Arrays.sort(array);
        for (int num : array) {
            System.out.println(num);
        }
    }
}



2. Coding for Work, Personal Use, and Productivity Increases:

Java is widely used in various professional fields, and ChatGPT can significantly contribute to the efficiency and productivity of developers. With ChatGPT, professionals can obtain customized Java code solutions tailored to their specific work requirements. Whether it is creating a data structure, implementing algorithms, or designing efficient database interactions, ChatGPT can generate code snippets that accelerate development processes. Similarly, ChatGPT can be a valuable resource for personal projects, such as developing applications, games, or automation scripts. By leveraging ChatGPT's outputs, people can efficiently accomplish tasks that would otherwise require extensive coding training. This enables users with limited programming experience to engage in meaningful projects, fostering creativity and exploration.

Example 2: Creating a Simple Calculator

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();
        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();
        double sum = num1 + num2;
        System.out.println("The sum is: " + sum);
    }
}



3. Expanding Java Programming Skills with ChatGPT:

Learning to code is a continuous journey, and ChatGPT can serve as a valuable learning tool for Java programming enthusiasts. By engaging with ChatGPT and exploring different prompts and generated code snippets, users can gain insights into alternative coding approaches and enhance their problem-solving abilities. Furthermore, ChatGPT can provide explanations and suggestions, allowing users to grasp new concepts and broaden their understanding of Java programming.

Example 3: Generating Fibonacci Sequence

public class Fibonacci {
    public static void main(String[] args) {
        int n = 10;
        int[] fibonacci = new int[n];
        fibonacci[0] = 0;
        fibonacci[1] = 1;
        for (int i = 2; i < n; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
        }
        for (int num : fibonacci) {
            System.out.println(num);
        }
    }
}




 The advent of language models like ChatGPT has transformed the way we approach coding in Java. By harnessing the capabilities of ChatGPT, users can generate unique Java code snippets tailored to their specific needs. This not only contributes to increased productivity and efficiency in work-related tasks but also enables individuals to undertake personal projects and learn and enhance their Java programming skills. With ChatGPT as a valuable resource, coding in Java becomes more accessible, empowering developers and enthusiasts alike to explore new horizons and embrace the possibilities of programming.



Monday, June 17, 2013

Java Arrays / FIle input / File output


-->

Java Programming Assignment For Arrays, File Input, And File Output


For use in Eclipse.

A teacher has 10 students who have taken the course.  The teacher uses the following grading scale to assign a letter grade to a students, based on the average of his or her four test scores:
Avg Test score  Letter grade
90-100 A
  1. B
  1. C
  1. D
  1. E

Assume that teacher has stored the following information in different files:
Lname.txt stores last names of students (string)
Fname.txt stores first names of students (string)
Exam1.txt stores exam 1 score (double)
Exam 2.txt stores exam 2 score (double)
Exam 3.txt stores exam 3 score (double)
Exam 4.txt stores exam 4 score (double)

In each case, the corresponding entries match in each file, that means, first element of each file corresponds to the first student, second for second student and so on.
Write a program that reads data from each file and stores in a separate array, except that String array named fullName contains the string representing full name of the student as follows:  "John Kennedy"  where "Kennedy" is picked up from Lname.txt, and "John" is selected from corresponding position in Fname.txt file. Create double arrays named Ex1, Ex2, Ex3, and Ex4 to score corresponding scores read from the files. 

Write the following methods:getAvg (to return average of all elements of an array passed as a parameter), 
getMax  (to find the largest element of an array passed as a parameter),
getMin (to find the smallest element of an array passed as a parameter).
computeAverage method which accepts 4 double parameters (for each exam score) and returns a double value representing the average. computeGrade method which accepts a double value (average) and returns a letter grade (char type). 

Using computeAverage method, compute and store the average for each student in a double array titled exAvg.

Using computeGrade method, compute and store the letter grade for each student in a char array titled grade


Output
After calculating the average test score, and the grade for each student, obtain the following output (on console using printf statement): Tabulated output for students with proper heading (sample output) – first line is the header --

Full Name of Student  Ex1 Ex2 Ex3 Ex4 Avg Grade
John Kennedy 78.0 73.0 83.0 78.0  78.0
(for all students) etc.

Print the statistics for each exam (by using appropriate method calls)

Exam Number  Max. Score  Min Score  Average Score
Exam 1 99.2 43.9 72.9 
Similarly, print these values for Exam 2, Exam 3, Exam 4, and AvgTestScore. 


Creation of Data sets

For each of the data sets, first 5 entries are to be entered as shown—Add another 5 entries of your choice data

Lname.txt Fname.txt Exam1.txt Exam2.txt Exam3.txt Exam4.txt

Gates  Lisa 87 76 92 88

Kramer Bill 65 72 83 64

Winfry Susan 91 90 87 99

Einstein Matt 57 75 79 56

Jobs Cindy 74 84 94 97

(add 5 more entries in each file of your choice)


Make the files yourself using a text edit program on your computer and put them into your project computer in eclipse

Here is the code for the assignment. You'll have to indent it yourself


import java.io.File;

import java.io.IOException;

import java.io.PrintStream;

import java.util.ArrayList;

import java.util.Scanner;



/**

 * 

 * @param args

 */

public class EnterYourClassNameHere{


public static double[] readScoreFile(String fileName) throws IOException {

// Read the file name and store it

double value;
ArrayList<Double> result = new ArrayList<Double>();
Scanner sc = new Scanner(new File(fileName));
while (sc.hasNextDouble()) {
value = sc.nextDouble();
result.add(value);
}
sc.close();
double[] arr = new double[result.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = result.get(i);
}
return arr;
}
public static ArrayList<String> readFile(String fileName)
throws IOException {
// Read Name and Store names
ArrayList<String> result = new ArrayList<String>();
Scanner sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (!line.equals("")) {
result.add(line);
}
}
sc.close();
return result;
}
// Read Array full name
public static String[] readFullName(String fnameFile, String lnameFile)
throws Exception {
ArrayList<String> fname = readFile(fnameFile);
ArrayList<String> lname = readFile(lnameFile);
int size = fname.size();
if (size > lname.size()) {
size = lname.size();
}
String[] fullName = new String[size];
for (int i = 0; i < size; i++) {
fullName[i] = fname.get(i) + " " + lname.get(i);
}
return fullName;
}
// return Average
public static double getAvg(double[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
// Return max
public static double getMax(double[] arr) {
double max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
}
// return Min
public static double getMin(double[] arr) {
double min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
return min;
}
// Compute Average
public static double computeAverage(double score1, double score2,
double score3, double score4) {
return (score1 + score2 + score3 + score4) / 4;
}
// Score
public static char computeGrade(double score) {
if (score >= 90) {
return 'A';
else if (score > 80) {
return 'B';
else if (score > 70) {
return 'C';
else if (score > 60) {
return 'D';
else {
return 'E';
}
}
// For output
public static void main(String[] args) throws Exception {
String[] fullName = readFullName("Fname.txt""Lname.txt");
double[] Ex1 = readScoreFile("Exam1.txt");
double[] Ex2 = readScoreFile("Exam2.txt");
double[] Ex3 = readScoreFile("Exam3.txt");
double[] Ex4 = readScoreFile("Exam4.txt");
char[] grade = new char[fullName.length];
double[] exAvg = new double[fullName.length];
for (int i = 0; i < grade.length; i++) {
exAvg[i] = computeAverage(Ex1[i], Ex2[i], Ex3[i], Ex4[i]);
grade[i] = computeGrade(exAvg[i]);
}
PrintStream ps = new PrintStream(new File("PA9OutFile.txt"));
System.out
.println("Full Name of Student    Ex1 Ex2 Ex3 Ex4 Avg Grade");
ps.println("Full Name of Student Ex1 Ex2 Ex3 Ex4 Avg Grade");
System.out.println("-----------------------------------------------------------");
ps.println("-----------------------------------------------------------");
for (int i = 0; i < grade.length; i++) {
System.out.println(String.format("%-23s %5.1f %5.1f %5.1f %5.1f %5.1f %c", fullName[i],
Ex1[i], Ex2[i], Ex3[i], Ex4[i], exAvg[i], grade[i]));
ps.println(String.format("%-23s %5.1f %5.1f %5.1f %5.1f %5.1f %c",
fullName[i], Ex1[i], Ex2[i], Ex3[i], Ex4[i], exAvg[i],grade[i]));
}
System.out.println();
ps.println();
System.out
.println("Exam Number Max Score Min Score Average Score");
ps.println("Exam Number Max Score Min Score Average Score");
System.out
.println("-----------------------------------------------------");
ps.println("----------------------------------------------------");
double min = getMin(Ex1);
double max = getMax(Ex1);
double avg = getAvg(Ex1);
System.out.println(String.format("Exam1 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam1 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex2);
max = getMax(Ex2);
avg = getAvg(Ex2);
System.out.println(String.format("Exam2 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam2 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex3);
max = getMax(Ex3);
avg = getAvg(Ex3);
System.out.println(String.format("Exam3 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam3 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex4);
max = getMax(Ex4);
avg = getAvg(Ex4);
System.out.println(String.format("Exam4 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam4 %3.1f %3.1f %3.1f", max, min,avg));
ps.close();
}
}













Java Program Loops, Frequency Count using loops


Java Program for Loops in Eclipse.

Java assignment

Problem to Solve
This assignment is to solve problem using loops. Write a program to generate 100 random integers in the range of 0 and 99999, find the frequency count of each digit (0, 1, 2, . . . , 9) in these numbers, and print a frequency histogram.
How to Do It
The Overall program structure may look like this:
  1. Use ten variables for the frequency counts for the ten digits 0, 1, 2, . . . , 9. 
  2. Other variables are also needed. For example, a variable to hold a random number, a variable 
    for the digit, etc. 
  3. Repeat 100 times (a loop): 
    • Generate a random number. 
    • For each digit in the number, increase the frequency count of by 1. This is done 
      using a loop. Note: we do not know how many digits are in the number. 
  4. For each digit from 0 to 9 (a loop): 
    • Store its frequency count into a variable.• Display the digit and the frequency count.• Display the horizontal frequency bar of asterisks using a loop. 
To accomplish the task, Here are some suggestions:
  1. Generate random integers in the range [0, 99999]. Assume the variable is number
             number = (int)(Math.random() * 99999);
    
  2. Get the digits of the random number. Since we do not know how many digits in the number, you need to use a loop to “peel off” the rightmost digit one at a time using integer division (/) and modulus (%) operations. Here are some example of random numbers and their digits: 
number digits
4028 4028 75 75 66 93540 94540
3. Print a horizontal bar. For each digit (say digit 5) with a frequency count (say 41), a bar is displayed with 41 asterisks like this
         5 (41): *****************************************




The code used for java in Eclipse is


import java.util.Scanner;
public class Enter Your Class Name Here {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Declare the Variables
int count = 0, count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 
int digit1= 1, digit2 = 1, digit3 = 1, digit4 = 1, digit5 = 1;
int num = 1;
//Loop
while (count<100){
num = (int)(Math.random() * 99999); // to generate a random number
count++;
//Break Numbers
digit1 = num / 10;
digit2 = (num % 10000) / 1000;
digit3 = ((num % 10000) % 1000) / 100;
digit4 = (((num % 10000) % 1000) % 100) / 10;
digit5 = ((((num % 10000) % 1000) % 100) % 10);
if(digit1 == 0 || digit2 == 0 || digit3 == 0 || digit4 == 0 || digit5 == 0){
count0 = count0 +1;}
if(digit1 == 1 || digit2 == 1 || digit3 == 1 || digit4 == 1 || digit5 == 1){
count1 = count1 +1;}
if(digit1 == 2 || digit2 == 2 || digit3 == 2 || digit4 == 2 || digit5 == 2){
count2 = count2 +1;}
if(digit1 == 3 || digit2 == 3 || digit3 == 3 || digit4 == 3 || digit5 == 3){
count3 = count3 +1;}
if(digit1 == 4 || digit2 == 4 || digit3 == 4 || digit4 == 4 || digit5 == 4){
count4 = count4 +1;}
if(digit1 == 5 || digit2 == 5 || digit3 == 5 || digit4 == 5 || digit5 == 5){
count5 = count5 +1;}
if(digit1 == 6 || digit2 == 6 || digit3 == 6 || digit4 == 6 || digit5 == 6){
count6 = count6 +1;}
if(digit1 == 7 || digit2 == 7 || digit3 == 7 || digit4 == 7 || digit5 == 7){
count7 = count7 +1;}
if(digit1 == 8 || digit2 == 8 || digit3 == 8 || digit4 == 8 || digit5 == 8){
count8 = count8 +1;}
if(digit1 == 9 || digit2 == 9 || digit3 == 9 || digit4 == 9 || digit5 == 9){
count9 = count9 +1;}
}
System.out.println("\n0" + "(" + count0 + ")");
for (int i = 0; i < count0; i++){
System.out.print("*");}
System.out.println("\n1" + "(" + count1 + ")");
for (int i = 0; i < count1; i++){
System.out.print("*");}
System.out.println("\n2" + "(" + count2 + ")");
for (int i = 0; i < count2; i++){
System.out.print("*");}
System.out.println("\n3" + "(" + count3 + ")");
for (int i = 0; i < count3; i++){
System.out.print("*");}
System.out.println("\n4" + "(" + count4 + ")");
for (int i = 0; i < count4; i++){
System.out.print("*");}
System.out.println("\n5" + "(" + count5 + ")");
for (int i = 0; i < count5; i++){
System.out.print("*");}
System.out.println("\n6" + "(" + count6 + ")");
for (int i = 0; i < count6; i++){
System.out.print("*");}
System.out.println("\n7" + "(" + count7 + ")");
for (int i = 0; i < count7; i++){
System.out.print("*");}
System.out.println("\n8" + "(" + count8 + ")");
for (int i = 0; i < count8; i++){
System.out.print("*");}
System.out.println("\n9" + "(" + count9 + ")");
for (int i = 0; i < count9; i++){
System.out.print("*");}
}
}


Java Switch Statements for Eclipse


Java Program for Switch Statements for the Programming Environment Eclipse



ObjectiveTo learn and practice with multi-way selections using switch statements. Problem Description
Your friend Jackie in Detroit is planning for a vacation. She needs to choose one destination from three possible locations. There are only two approaches for transportation – either drive or fly. If she drives, the gas price is $3.89 per gallon (assume same price across the country) and the average gas mileage of her car is 24 miles per gallon. If she flies, the airfare depends on the destination from Detroit. To Washington DC, she may choose either fly or drive. The meal cost depends on the type of the location: regular ($31 per day) and high-cost ($52 per day).
She will stay at a hotel of her choice at the destination for 3 days. The costs of the hotel rooms are shown below (assume the hotels of the same hotel chain cost the same across the country):
Write a Java program to help Jackie to figure out the cost of the trip (round trip).
Requirements:
  1. Must include a well-written program description to describe the task of the problem. 
  2. Use named constants for the fixed values. 
  3. Display a menu for the user to make a selection. The menu items may be labeled 1, 2, 3, etc. Use switch statements to handle the user’s selection of destination and corresponding transportation method. Assign values to appropriate variables according to user’s selection. Check the validity of user’s inputs using default clause in switch statements. Terminate the execution using System.exit(1); when an invalid input is encountered. 
  4. Do the same for hotel selection. 
  5. Correctly calculate the costs for transportation (round trip), hotel, meals, and the total. 
destination
transportation
airfare
(round trip) 
driving distance
(one way)
meal
Cleveland
drive
169 miles
regular
Las Vegas
fly
$507
high cost
Washington DC 
drive or fly
$328
526 miles
high cost
hotel
cost per day
Comfort Inn 
$85
Marriott
$159
Hyatt
$238
page1image42320

page2image1016
6. The output produced by your program should include itemized costs (i.e. cost of transportation, cost of hotel, and cost of meals) in addition to the total cost, and must be descriptive and well formated.
7. Test your program with various input data, including the minimum of the following:
• Travel to Cleveland, stay at Comfort Inn. • Travel to Las Vegas, stay at Marriott.• Drive to Washington DC, stay at Marriott. • Fly to Washington DC, stay at Hyatt.
• Invalid input.
A sample run may look like this:

Here are the places you may go for vacation.
--------------------------------------------
   1. Cleveland
   2. Las Vegas
   3. Washington DC
--------------------------------------------
Please select the number of the destination --> 3
To Washington DC, do you want to drive (’d’) or fly (’f’)? d
These are the hotels having vacancies:
----------------------------------------
1. Comfort Inn
2. Marriott
3. Hyatt
$ 85.00
$159.00
$238.00
----------------------------------------
Please make your selection --> 2
Cost for your trip:
(drive to Washington DC, staying at Marriott for 3 days):
           ---------------------------
             Trasportation  $ 170.51
             Hotel cost   : $ 477.00
             Cost of meals: $ 156.00
           ---------------------------
             Total cost   : $ 803.51
           ---------------------------
Have a nice vacation!






The Code for this program is 


import java.util.Scanner;
public class Enter Your Class Here{
/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int destination;
int distance=1;
String dest= "dest";
double transportation;
double airfare, drivingdistance,gallon;
final double regularMeal= 31;
final double highMeal= 52;
double flying, driving;
double gasPrice = 3.89;
final String dest1 = "Cleaveland";
final String dest2 = "Las Vegas";
final String dest3 = "Washington DC";
String hotel0 = "hotel";
final String hotel1= "Comfort Inn ";
final String hotel2= "Marriott";
final String hotel3= "Hyatt";
final double gasMileage = 24.00;
double totaltran = 0 ;
final String cityName;
int hotel=0;
double hotelcost =1;
double mealtotal=0;
int travel =0;
//Users Input
System.out.println(" \t 1 \t \t Cleveland \t");
System.out.println(" \t 2 \t \t Las Vegas \t");
System.out.println(" \t 3 \t \t Washington \t");
System.out.println("Please select the number of the destination?");
destination = input.nextInt();
System.out.println("To" + destination + "do you want to drive ('1') or fly ('2')?");
travel= input.nextInt();
System.out.println("These are the hotels having vacancies:");
System.out.println(" \t 1 \t \t Comfort Inn\t $85.00");
System.out.println(" \t 2 \t \t Marriott \t $159.00");
System.out.println(" \t 3 \t \t Hyatt \t\t $238.00");
System.out.println("Please make your hotels selection");
hotel = input.nextInt();
//Body
switch(destination){
case 1 :dest = dest1;
distance = 169;
totaltran= ((distance = 169*2)/gasMileage)*gasPrice;
mealtotal= regularMeal*3;
break;
case 2 :dest = dest2;
totaltran=507;
mealtotal = highMeal*3;
break;
case 3 : dest = dest3;
mealtotal= highMeal*3;
switch(travel){
case 1: totaltran= ((distance = 526*2)/gasMileage)*gasPrice;
distance = 526;
break;
case 2: totaltran = 328;
break;
}
break;
default:
}
switch(hotel) {
case 1: hotel0=hotel1;
hotelcost = 3 * 85;
break;
case 2: hotel0=hotel2;
hotelcost = 3 * 159;
break;
case 3: hotel0= hotel3;
hotelcost = 3 * 238;
break;
default: System.out.println("hotels doesnt exist");
}
//Calculate and Print Cost 
System.out.println("Cost For Your Trip:");
System.out.println("(Drive to " + dest + ", staying at " + hotel0 + " for 3 days.):");
System.out.println("-----------------------------------------------");
System.out.printf("Transportation $ %4.2f\n" ,totaltran);
System.out.printf("Hotel Cost : $ %4.2f\n" , hotelcost);
System.out.printf("Cost of meals: $ %4.2f\n" , mealtotal);
System.out.println("-----------------------------------------------");
System.out.printf("Total cost : $ %1.2f\n" , totaltran + hotelcost+ mealtotal);
}
}