/* * * To generate weather for location at longitude -98.76 and latitude 26.70 for * the month of February do: * java WeatherGenerator -98.76 26.70 3 * * Remember that January is 2, February is 3 and so on. */ public class Main { static final int WET = 1; // Use this value for a wet day static final int DRY = 2; // Use this value for a dry day // Number of days in each month, January is index 0, February is index 1 static final int[] numberOfDaysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /* * Given a location (longitude, latitude) in the USA and a month of the year, the method * returns the forecast for the month based on the drywet and wetwet transition * probabilities tables. * * month will be a value between 2 and 13: 2 corresponds to January, 3 corresponds to February * and so on. These are the column indexes of each month in the transition probabilities tables. * * The first day of the month has a 50% chance to be a wet day, 0-0.49 (wet), 0.50-0.99 (dry) * * Use StdRandom.uniform() to generate a real number uniformly in [0,1) * */ public static int[] oneMonthGenerator(double longitute, double latitude, int month, double[][] drywet, double[][] wetwet) { // WRITE YOUR CODE HERE int monthIndex = 12; int days = 1; int[][] monthArray = new int[monthIndex][days]; monthArray[0][0] = 31; monthArray[1][0] = 28; monthArray[2][0] = 31; monthArray[3][0] = 30; monthArray[4][0] = 31; monthArray[5][0] = 30; monthArray[6][0] = 31; monthArray[7][0] = 31; monthArray[8][0] = 30; monthArray[9][0] = 31; monthArray[10][0] = 30; monthArray[11][0] = 31; int arrayLen = monthArray[month-2][0]; int[] forecast = new int[arrayLen]; int randomeNum = StdRandom.uniform(0,1); if(randomeNum < 0.5) forecast[0] = WET; else forecast[0] = DRY; for(int i = 1; i<arrayLen; i++) { randomeNum = StdRandom.uniform(0,1); if(forecast[i-1] == WET) { if(randomeNum <= 0.45) forecast[i] = WET; else forecast[i] = DRY; } else { if(randomeNum <= 0.12) forecast[i] = WET; else forecast[i] = DRY; } } return forecast; } /* * Returns the number of mode (WET or DRY) days in forecast. */ public static int numberOfWetDryDays (int[] forecast, int mode) { int count = 0; int arrayLen = forecast.length; for(int i =0; i<arrayLen; i++) { if(forecast[i] == mode) { count++; } } return count; } /* * Returns the longest number of consecutive mode (WET or DRY) days in forecast. */ public static int lengthOfLongestSpell (int[] forecast, int mode) { int longest = 0; int tempLongest = 0; int arrayLen = forecast.length; for(int i=0; i<arrayLen; i++) { if(forecast[i] == mode) { tempLongest++; } else { if(tempLongest > longest) longest = tempLongest; tempLongest = 0; } } return longest; } /* * Reads numberOfLocations probabilites into arrayToFill. * * Transition probabilities file format: * Longitude Latitude January February March April May June July August September October November December * -97.58 26.02 0.76 0.75 0.77 0.74 0.80 0.86 0.94 0.97 0.89 0.77 0.74 0.77 */ public static void readTransitionProbabilities ( double[][] arrayToFill, int numberOfLocations ) { int row = 0; while (row < numberOfLocations) { arrayToFill[row][0] = StdIn.readDouble(); // Longitute arrayToFill[row][1] = StdIn.readDouble(); // Latitude arrayToFill[row][2] = StdIn.readDouble(); // January arrayToFill[row][3] = StdIn.readDouble(); // February arrayToFill[row][4] = StdIn.readDouble(); // March arrayToFill[row][5] = StdIn.readDouble(); // April arrayToFill[row][6] = StdIn.readDouble(); // May arrayToFill[row][7] = StdIn.readDouble(); // June arrayToFill[row][8] = StdIn.readDouble(); // July arrayToFill[row][9] = StdIn.readDouble(); // August arrayToFill[row][10] = StdIn.readDouble(); // Septmber arrayToFill[row][11] = StdIn.readDouble(); // October arrayToFill[row][12] = StdIn.readDouble(); // November arrayToFill[row][13] = StdIn.readDouble(); // December row += 1; } } /* * * Expects files in the same directory. The first (drywet.txt) contains * transition probabilities that reflects how often the weather changes * from wet to dry. The second (wetwet.txt) is transition probabilities * that reflects that the weather remains wet from one day to the next. * */ public static void populateTransitionProbabilitiesArrays(double[][] drywet, double[][] wetwet, int numberOfLocations) { // Read transition probabilities that reflects how often the weather // changes from wet to dry into 2D array drywet. // The first line on the file has number of locations (lines) StdIn.setFile("drywet.txt"); readTransitionProbabilities(drywet, numberOfLocations); // Read transition probabilities that reflects that the weather remains // wet from one day to the next into 2D array wetwet. // The first line on the file has number of locations (lines) StdIn.setFile("wetwet.txt"); readTransitionProbabilities(wetwet, numberOfLocations); } /* * * Reads the files containing the transition probabilities for US locations. * * To find * * Execution: * java WeatherGenerator -97.58 26.02 3 * * */ public static void main (String[] args) { int numberOfRows = 4001; // Total number of locations int numberOfColumns = 14; // Total number of 14 columns in file // File format: longitude, latitude, 12 months of transition probabilities // Allocate and populate arrays that hold the transition probabilities double[][] drywet = new double[numberOfRows][numberOfColumns]; double[][] wetwet = new double[numberOfRows][numberOfColumns]; populateTransitionProbabilitiesArrays(drywet, wetwet, numberOfRows); /*** WRITE YOUR CODE BELLOW THIS LINE. DO NOT erase any of the lines above. ***/ // Read command line inputs double longitute = Double.parseDouble(args[0]); double latitude = Double.parseDouble(args[1]); int month = Integer.parseInt(args[2]); int[] forecast = oneMonthGenerator(longitute, latitude, month, drywet, wetwet); int drySpell = lengthOfLongestSpell(forecast, DRY); int wetSpell = lengthOfLongestSpell(forecast, WET); System.out.println("There are " + forecast.length + " days in the forecast for month " + month); System.out.println(drySpell + " days of dry spell."); System.out.println(wetSpell + " days of wet spell."); for ( int i = 0; i < forecast.length; i++ ) { // This is the ternary operator. (conditional) ? executed if true : executed if false String weather = (forecast[i] == WET) ? "Wet" : "Dry"; System.out.println("Day " + (i+1) + " is forecasted to be " + weather); } } }
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |