Java

Here’s a list of Java scripts that I have made, in the process of learning actual programming languages.  Also includes some cool links.

This page is mostly listed for my own benefit, should I need to write something and not be at my battlestation.  Please don’t just copy and paste (I’m sure these homework assignments will be in circulation for some time), but do give them a shot if you want to review the functions used.

 

Links

Eclipse Compiler
Pretty solid compiler.  Can be used for several different languages.
Versions

Online Compiler
For when I/you are stuck in some library/Mathlab and want to program.
Tutorialspoint – Jdoodle

Class and Object Initilization
Good refresher for how classes and objects are initialized, and why.
JavaWorld

 

Scripts

Two ASCII rockets, Classes, some Variable Types


public class TwoRockets {
	
	// Initialize reps; how many rockets are drawn
	public static final int REPS = 2;
	
	// Main method; calls the different draw methods
	public static void main(String[] args) {
		drawTip();
		drawLine();
		drawEmpty();
		drawEmpty();
		drawLine();
		drawWord("United");
		drawWord("States");
		drawLine();
		drawEmpty();
		drawEmpty();
		drawLine();
		drawTip();
	}
	
	// Draw methods
	public static void drawTip() {
		// Repeats based on the REPS variable
		for(int i = 1; i <= REPS; i++){
			System.out.print("   /\\    ");
		}
		// And prints out a line after the repeats
		System.out.println(" ");
		
		
		// Next part
		for(int i = 1; i <= REPS; i++){
			System.out.print("  /  \\   ");
		}
		System.out.println(" ");
		
		
		// Next part
		for(int i = 1; i <= REPS; i++){
			System.out.print(" /    \\  ");
		}
		System.out.println(" ");
	}
	
	public static void drawLine() {
		for(int i = 1; i <= REPS; i++){
			System.out.print("+------+ ");
		}
		System.out.println(" ");
	}
	
	public static void drawEmpty() {
		for(int i = 1; i <= REPS; i++){
			System.out.print("|      | ");
		}
		System.out.println(" ");
	}
	
	public static void drawWord(String word) {
		for(int i = 1; i <= REPS; i++){
			System.out.print("|" + word + "| ");
		}
		System.out.println(" ");
	}
	
	
}

Count Numbers, Powers of 2, For Repeat, import java.math


import java.math.*;


public class WeekThree {
	
	
	
	public static void printNumbers (int maximum){
		// Repeat 'maximum' times
		for(int i = 0; i <= maximum; i++){
			System.out.print("[" + i + "] ");
		}
		
		// And an end-line for neatness-sake
		System.out.println("");
	}
	
	
	
	public static void printPowersof2 (int numeral){
		// Prepare an int
		int value;
		
		// Repeat 'numeral' times
		for(int i = 0; i <= numeral; i++){
			
			// Set value to the math.pow and then print it
			value = (int) Math.pow(2, i);
			System.out.print(value + " ");
		}
		
		// And an end-line for neatness-sake
		System.out.println("");
	}
	
	
	
	
	
	
	// Alternate printPowers class that does not need the Math function
	public static void printPowersof2alt (int numeral){
		// Prepare an int
		int value;
		
		// Repeat numeral+1 times
		for(int i = 1; i <= numeral+1; i++){

			// If i=1 then return 1, otherwise continue
			if (i==1){
				value=1;
			}
			else{
				// Set value to 2
				value = 2;
				
				// Multiply the value each time for the current 'i' size
				for (int q = 2; q< i; q++){
					value = value * 2;
				}
			}
			
			// Print the result
			System.out.print(value + " ");
			
		}
		
		// And an end-line for neatness-sake
		System.out.println("");
		
	}
	
}

Basic Graphics, import java.awt


import java.awt.*;

public class Graphics {
	
	public static void main(String[] args) {
		// Create the drawing panel
		DrawingPanel panel = new DrawingPanel(400, 400);
		panel.setBackground(Color.MAGENTA);
		
		// Draw three lines to form a triangle
		Graphics2D g = panel.getGraphics();
		g.drawLine(50, 150, 202, 177);
		g.drawLine(200, 175, 100, 300);
		g.drawLine(52, 148, 102, 300);

		// Draw a circle
		g.setColor(Color.CYAN);
		g.fillOval(250,250,100,100);
		g.setColor(Color.BLACK);
		g.drawOval(250,250,100,100);
		
		// Draw some text
		g.setColor(Color.YELLOW);
		g.setFont(new Font("Serif",Font.BOLD + Font.ITALIC, 24));
		g.drawString("THIS IS TEXT, HOW ARE YOU",  50, 50);
		
	}
	
}

Reverse String, Input Scanner, Equals, import java.util.Scanner


import java.util.Scanner;


public class ReverseString{

     public static void main(String []args){
       
    	 // Initialize variables needed
    	 String input = "";
    	 String output = "";
    	 int leng = 0;
    	 
    	 // Create scanner object and ask for input
    	 Scanner scan = new Scanner(System.in);
    	 
    	 // Ask for input
    	 System.out.print("Enter a word >>> ");
		 
    	 // Get next input
    	 input = scan.nextLine();
    	 // input = "Racecar";
    	 System.out.println(input);
    	 input = input.toLowerCase();
    	 input = input.replaceAll("\\s", "");
    	 input = input.replaceAll("'", "");
    	 input = input.replaceAll(",", "");
    	 
    	 // Get length of input
    	 leng = input.length();

    	 // Repeat through length
    	 for (int i=leng-1; i>=0; i--){
    		 output = output + input.charAt(i); 
    	 }
       
    	 // Print the input and output
    	 System.out.println(input + " -> " + output);
       
       
    	 // Check if is the same reverse
    	 if (input.equals(output)){
    		 System.out.println("\nYour word is a palindrome!");
    	 }
    	 else{
    		 System.out.println("\nYour word is not a palindrome."); 
    	 }
       
       
     }
}

Open File, Read Numbers, Throws Exception, Scanners, import java.util.Scanner, import java.io


import java.util.Scanner;
import java.io.*;
import java.io.*;

public class evenNumbers{
  public static void main(String[] args) throws FileNotFoundException{
    
    // Prepare variables
    int temp = 0;
    int num = 0;
    int sum = 0;
    int evens = 0;
    
    // Load info from the file
    File f = new File("numbers.txt");
    Scanner input = new Scanner(f);
    
    // Loop through file input, grabbing integers as we go
    while (input.hasNext()){
      
      if (input.hasNextInt()){
      	num++;

        temp=input.nextInt();
        sum+=temp;

        // Even?
        if (temp % 2 == 0){
          evens++;
        }
      }
    }
    
    // Print the results
    String percentage = String.format("%1.2f", ((((double) evens) / num ) * 100));
    
    System.out.println(num + " numbers, sum = " + sum);
    System.out.println("");
    System.out.println(evens + " evens (" + percentage + "%)");
    
  }
}

Read File, Loop Through Words, import java.util.Scanner, import java.io


import java.util.Scanner;
import java.io.*;

public class collapseSpaces{
  public static void main(String[] args) throws FileNotFoundException{
	  
	  // Initialize the scanner for both the console and file target
	  Scanner console = new Scanner(System.in);
	  Scanner input = chooseFile(console);
	  
	  // Loop through file input, grabbing words as we go
	  while (input.hasNext()){
		  System.out.print(input.next()+" ");
	  }
	  
  }
  
  
  // Ask for the file name
  public static Scanner chooseFile(Scanner console) throws FileNotFoundException{
	  
	  // Print and ask for file
      System.out.print("File name?: ");
      
      // Try to initialize that file if able
      File f = new File(console.nextLine());
      
      // While unable to keep asking
      while(!f.canRead()){
        System.out.println("File cannot be found.");
        System.out.print("File name?: ");
        f = new File(console.nextLine());
      }
      
      // Return that scanner for the file when succesful
      return new Scanner(f);
  }
}

Technically Animated Graphics, Grahpics, Sleep, import java.awt


import java.awt.*;

public class animatedFace{
	
	public static void main(String [] args) {
		
		// Prepare drawing panel
		DrawingPanel panel = new DrawingPanel(600,600);
		Graphics2D g = panel.getGraphics();
		
		// Loop like 10 times, changing the numbers and drawing a new face each time
		int fine = 0;
		while(fine<10){ panel.setBackground(Color.RED); face(1,g); panel.sleep(100); panel.setBackground(Color.ORANGE); face(2,g); panel.sleep(100); panel.setBackground(Color.YELLOW); face(3,g); panel.sleep(100); panel.setBackground(Color.GREEN); face(4,g); panel.sleep(100); panel.setBackground(Color.CYAN); face(5,g); panel.sleep(100); panel.setBackground(Color.BLUE); face(6,g); panel.sleep(100); panel.setBackground(Color.MAGENTA); face(7,g); panel.sleep(100); panel.setBackground(Color.PINK); face(8,g); panel.sleep(100); fine++; } // Create the drawing panel } private static void face(int n, Graphics g){ // Initialize color array and the color ints to correspond to those colors Color co[] = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA, Color.PINK}; int first = n; int second = n-1; // Prevent out of bounds if (first>7){first=0;}
		
		// Draw the main part of the face
		g.setColor(co[first]);
		g.fillOval(100,100,400,400);
		
		// Draw the mouth
		g.setColor(co[second]);
		g.fillOval(150,320,300,120);
		
		// Draw the eyes
		g.fillOval(160,170,120,120);
		g.fillOval(320,170,120,120);
		
		// Cover some of the mouth
		g.setColor(co[first]);
		g.fillOval(150,280,300,120);
		
	}
	
}

Date Classes, While Loops, Arrays, Objects, Encapsulation


class Date{
	
	// Standard variables
	private int day;
	private int month;
	private int year;
	private boolean leapYear;
	
	// Constructs a new date with the d/m/y and leap variables
	public Date(int iyear, int imonth, int iday){
		day = iday;
		month = imonth;
		year = iyear;
		leapYear = false;
		
		// Calculate if a leap year or not
		leapYear = isLeapYear();
	}
	
	
	// Return the parts of the date when called
	public int getYear(){return(year);}
	public int getMonth(){return(month);}
	public int getDay(){return(day);}
	
	
	// Returns the day of the week
	public String getDayOfWeek(){
		
		// Create weekday int and START date for the start of the calendar 
		int weekday = 0;
		Date start = new Date(1753,1,1);

		// Count the days from this start date to now then delete the start calender date
		weekday = start.advanceTo(this) + 1;
		start = null;
		
		// Create array of day names, and the current day sort of
		String dayy[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
		
		// Remove extraneous weeks from the time since 1753
		while(weekday>7){weekday-=7;}
		
		// Return the remaining day's name
		if (weekday-1 < 0){weekday ++;}
		return(dayy[weekday-1]);
		
	}
	
	
	// returns how many days are in this month
	public int monthDays(){
		int dayz[] = {31,28,31,30,31,30,31,31,30,31,30,31};
		if (leapYear == true){dayz[1]=29;}
		
		return(dayz[month-1]);
	}
	
	
	// Recalculates the leap-year and returns the value as a bool
	public boolean isLeapYear(){
		boolean leap = false;
		
		if (year % 4 == 0){leap = true;}
		if ((year % 100 == 0) && (year % 400 > 0)){leap = false;}
		
		return(leap);
	}
	
	
	// Increments the day
	public void nextDay(){
		
		// If the day can fit in the month then great
		if (day+1 <= monthDays()){
			day++;
		}
		else{// If not then increment the month and set day to 1
			day = 1;
			month++;
			
			// Check if this pushes the date to a new year
			if (month > 12){
				month = 1;
				leapYear = isLeapYear();
			}
		}
	}
	
	
	// Increments the month and returns the days added
	public int nextMonth(){
		
		int advDays = 0;
		
		// Calculate the days remaining in this month
		advDays = (monthDays() - day) + 1;
		
		// Set day to 1 and increment month
		day = 1;
		month++;
		
		// Check if this pushes the date to a new year
		if (month > 12){
			month = 1;
			year ++;
			leapYear = isLeapYear();
		}
		
		return(advDays);
	}
	
	
	// Advances the date to the argument date and prints the amount of days that were added
	public int advanceTo(Date endDay){
		
		// First check if the days are equal, if so then return 0
		if (this.equals(endDay)){
			return(0);
		}
		else{// If not create the reached and advanced variables
			
			// Create temporary variables reached (for the while loop) and to count the increments
			boolean reached = false;
			int daysAdvanced = 0;
			int targetDay = endDay.getDay();
			int targetMonth = endDay.getMonth();
			int targetYear = endDay.getYear();
			
			// If the year is before then return -1
			if (endDay.getYear() month) || (targetYear > year)){
					daysAdvanced += nextMonth();
				}
				else{// Months/years are equal
					
					// Increment the day
					if (targetDay > day){
						daysAdvanced++;
						nextDay();
					}
					else{// When equal
						reached = true;
					}
				}
			}
			
			// End of while; finished getting the dates equal
			// Return the days passed as an int
			return(daysAdvanced);
			
		}
	}
	
	
	// Returns if this date and another are equal or not
	public boolean equals(Date d){
		if (this.year != d.year){
			return(false);
		}
		else if (this.month != d.month){
			return(false);
		}
		else if (this.day != d.day){
			return(false);
		}
		else{
			return(true);
		}
	}
	
	
	// returns info on the object
	public String toString(){
		String out;
		
		out = month + "/" + day + "/" + year + ",  Leap:" + leapYear;
		return(out);
	}
	
	
}