file_id stringlengths 5 10 | content stringlengths 96 41.7k | repo stringlengths 7 108 | path stringlengths 8 211 | token_length int64 28 8.19k | original_comment stringlengths 8 5.72k | comment_type stringclasses 2 values | detected_lang stringclasses 1 value | prompt stringlengths 43 41.7k |
|---|---|---|---|---|---|---|---|---|
198409_22 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.utils;
import java.util.Calendar;
import java.util.GregorianCalendar;
public enum Holiday {
NONE,
LUNAR_NEW_YEAR, //Varies, sometime in late Jan to Late Feb (7 days)
APRIL_FOOLS, //April 1st, can override easter (1 day)
EASTER, //Varies, sometime in Late Mar to Late Apr (6-7 days)
//Nothing in May
PRIDE, //Jun 24th to Jun 30th (7 days)
//Nothing in Jul
SHATTEREDPD_BIRTHDAY, //Aug 1st to Aug 7th (7 days)
//Nothing in Sept
HALLOWEEN, //Oct 24th to Oct 31st (7 days)
//Nothing in Nov
PD_BIRTHDAY, //Dec 1st to Dec 7th (7 days)
WINTER_HOLIDAYS, //Dec 15th to Dec 26th (12 days)
NEW_YEARS; //Dec 27th to Jan 2nd (7 days)
//total of 61-62 festive days each year, mainly concentrated in Late Oct to Early Feb
//we cache the holiday here so that holiday logic doesn't suddenly shut off mid-game
//this gets cleared on game launch (of course), and whenever leaving a game scene
private static Holiday cached;
public static void clearCachedHoliday(){
cached = null;
}
public static Holiday getCurrentHoliday(){
if (cached == null){
cached = getHolidayForDate((GregorianCalendar) GregorianCalendar.getInstance());
}
return cached;
}
//requires a gregorian calendar
public static Holiday getHolidayForDate(GregorianCalendar cal){
//Lunar New Year
if (isLunarNewYear(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR))){
return LUNAR_NEW_YEAR;
}
//April Fools
if (cal.get(Calendar.MONTH) == Calendar.APRIL
&& cal.get(Calendar.DAY_OF_MONTH) == 1){
return APRIL_FOOLS;
}
//Easter
if (isEaster(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR),
cal.getActualMaximum(Calendar.DAY_OF_YEAR) == 366)){
return EASTER;
}
//Pride
if (cal.get(Calendar.MONTH) == Calendar.JUNE
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return PRIDE;
}
//Shattered's Birthday
if (cal.get(Calendar.MONTH) == Calendar.AUGUST
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return SHATTEREDPD_BIRTHDAY;
}
//Halloween
if (cal.get(Calendar.MONTH) == Calendar.OCTOBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return HALLOWEEN;
}
//Pixel Dungeon's Birthday
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return PD_BIRTHDAY;
}
//Winter Holidays
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 15
&& cal.get(Calendar.DAY_OF_MONTH) <= 26){
return WINTER_HOLIDAYS;
}
//New Years
if ((cal.get(Calendar.MONTH) == Calendar.DECEMBER && cal.get(Calendar.DAY_OF_MONTH) >= 27)
|| (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) <= 2)){
return NEW_YEARS;
}
return NONE;
}
//has to be hard-coded on a per-year basis =S
public static boolean isLunarNewYear(int year, int dayOfYear){
int lunarNewYearDayOfYear;
switch (year){
//yes, I really did hardcode this all the way from 2020 to 2100
default: lunarNewYearDayOfYear = 31+5; break; //defaults to February 5th
case 2020: lunarNewYearDayOfYear = 25; break; //January 25th
case 2021: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2022: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2023: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2024: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2025: lunarNewYearDayOfYear = 29; break; //January 29th
case 2026: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2027: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2028: lunarNewYearDayOfYear = 26; break; //January 26th
case 2029: lunarNewYearDayOfYear = 31+13; break; //February 13th
case 2030: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2031: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2032: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2033: lunarNewYearDayOfYear = 31; break; //January 31st
case 2034: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2035: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2036: lunarNewYearDayOfYear = 28; break; //January 28th
case 2037: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2038: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2039: lunarNewYearDayOfYear = 24; break; //January 24th
case 2040: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2041: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2042: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2043: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2044: lunarNewYearDayOfYear = 30; break; //January 30th
case 2045: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2046: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2047: lunarNewYearDayOfYear = 26; break; //January 26th
case 2048: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2049: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2050: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2051: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2052: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2053: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2054: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2055: lunarNewYearDayOfYear = 28; break; //January 28th
case 2056: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2057: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2058: lunarNewYearDayOfYear = 24; break; //January 24th
case 2059: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2060: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2061: lunarNewYearDayOfYear = 21; break; //January 21st
case 2062: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2063: lunarNewYearDayOfYear = 29; break; //January 29th
case 2064: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2065: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2066: lunarNewYearDayOfYear = 26; break; //January 26th
case 2067: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2068: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2069: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2070: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2071: lunarNewYearDayOfYear = 31; break; //January 31st
case 2072: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2073: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2074: lunarNewYearDayOfYear = 27; break; //January 27th
case 2075: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2076: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2077: lunarNewYearDayOfYear = 24; break; //January 24th
case 2078: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2079: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2080: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2081: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2082: lunarNewYearDayOfYear = 29; break; //January 29th
case 2083: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2084: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2085: lunarNewYearDayOfYear = 26; break; //January 26th
case 2086: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2087: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2088: lunarNewYearDayOfYear = 24; break; //January 24th
case 2089: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2090: lunarNewYearDayOfYear = 30; break; //January 30th
case 2091: lunarNewYearDayOfYear = 31+18; break; //February 18th
case 2092: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2093: lunarNewYearDayOfYear = 27; break; //January 27th
case 2094: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2095: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2096: lunarNewYearDayOfYear = 25; break; //January 25th
case 2097: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2098: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2099: lunarNewYearDayOfYear = 21; break; //January 21st
case 2100: lunarNewYearDayOfYear = 31+9; break; //February 9th
}
//celebrate for 7 days total, with Lunar New Year on the 5th day
return dayOfYear >= lunarNewYearDayOfYear-4 && dayOfYear <= lunarNewYearDayOfYear+2;
}
//has to be algorithmically computed =S
public static boolean isEaster(int year, int dayOfYear, boolean isLeapYear){
//if we're not in March or April, just skip out of all these calculations
if (dayOfYear < 59 || dayOfYear > 121) {
return false;
}
//Uses the Anonymous Gregorian Algorithm
int a = year % 19;
int b = year / 100;
int c = year % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (a*19 + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (32 + 2*e + 2*i - h - k) % 7;
int m = (a + h*11 + l*22)/451;
int n = (h + l - m*7 + 114) / 31;
int o = (h + l - m*7 + 114) % 31;
int easterDayOfYear = 0;
if (n == 3){
easterDayOfYear += 59; //march
} else {
easterDayOfYear += 90; //april
}
if (isLeapYear) {
easterDayOfYear += 1; //add an extra day to account for February 29th
}
easterDayOfYear += (o+1); //add day of month
//celebrate for 7 days total, with Easter Sunday on the 5th day
return dayOfYear >= easterDayOfYear-4 && dayOfYear <= easterDayOfYear+2;
}
}
| 00-Evan/shattered-pixel-dungeon | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/Holiday.java | 4,181 | //Halloween | line_comment | nl | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.utils;
import java.util.Calendar;
import java.util.GregorianCalendar;
public enum Holiday {
NONE,
LUNAR_NEW_YEAR, //Varies, sometime in late Jan to Late Feb (7 days)
APRIL_FOOLS, //April 1st, can override easter (1 day)
EASTER, //Varies, sometime in Late Mar to Late Apr (6-7 days)
//Nothing in May
PRIDE, //Jun 24th to Jun 30th (7 days)
//Nothing in Jul
SHATTEREDPD_BIRTHDAY, //Aug 1st to Aug 7th (7 days)
//Nothing in Sept
HALLOWEEN, //Oct 24th to Oct 31st (7 days)
//Nothing in Nov
PD_BIRTHDAY, //Dec 1st to Dec 7th (7 days)
WINTER_HOLIDAYS, //Dec 15th to Dec 26th (12 days)
NEW_YEARS; //Dec 27th to Jan 2nd (7 days)
//total of 61-62 festive days each year, mainly concentrated in Late Oct to Early Feb
//we cache the holiday here so that holiday logic doesn't suddenly shut off mid-game
//this gets cleared on game launch (of course), and whenever leaving a game scene
private static Holiday cached;
public static void clearCachedHoliday(){
cached = null;
}
public static Holiday getCurrentHoliday(){
if (cached == null){
cached = getHolidayForDate((GregorianCalendar) GregorianCalendar.getInstance());
}
return cached;
}
//requires a gregorian calendar
public static Holiday getHolidayForDate(GregorianCalendar cal){
//Lunar New Year
if (isLunarNewYear(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR))){
return LUNAR_NEW_YEAR;
}
//April Fools
if (cal.get(Calendar.MONTH) == Calendar.APRIL
&& cal.get(Calendar.DAY_OF_MONTH) == 1){
return APRIL_FOOLS;
}
//Easter
if (isEaster(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR),
cal.getActualMaximum(Calendar.DAY_OF_YEAR) == 366)){
return EASTER;
}
//Pride
if (cal.get(Calendar.MONTH) == Calendar.JUNE
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return PRIDE;
}
//Shattered's Birthday
if (cal.get(Calendar.MONTH) == Calendar.AUGUST
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return SHATTEREDPD_BIRTHDAY;
}
//Hallo<SUF>
if (cal.get(Calendar.MONTH) == Calendar.OCTOBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return HALLOWEEN;
}
//Pixel Dungeon's Birthday
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return PD_BIRTHDAY;
}
//Winter Holidays
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 15
&& cal.get(Calendar.DAY_OF_MONTH) <= 26){
return WINTER_HOLIDAYS;
}
//New Years
if ((cal.get(Calendar.MONTH) == Calendar.DECEMBER && cal.get(Calendar.DAY_OF_MONTH) >= 27)
|| (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) <= 2)){
return NEW_YEARS;
}
return NONE;
}
//has to be hard-coded on a per-year basis =S
public static boolean isLunarNewYear(int year, int dayOfYear){
int lunarNewYearDayOfYear;
switch (year){
//yes, I really did hardcode this all the way from 2020 to 2100
default: lunarNewYearDayOfYear = 31+5; break; //defaults to February 5th
case 2020: lunarNewYearDayOfYear = 25; break; //January 25th
case 2021: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2022: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2023: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2024: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2025: lunarNewYearDayOfYear = 29; break; //January 29th
case 2026: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2027: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2028: lunarNewYearDayOfYear = 26; break; //January 26th
case 2029: lunarNewYearDayOfYear = 31+13; break; //February 13th
case 2030: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2031: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2032: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2033: lunarNewYearDayOfYear = 31; break; //January 31st
case 2034: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2035: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2036: lunarNewYearDayOfYear = 28; break; //January 28th
case 2037: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2038: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2039: lunarNewYearDayOfYear = 24; break; //January 24th
case 2040: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2041: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2042: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2043: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2044: lunarNewYearDayOfYear = 30; break; //January 30th
case 2045: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2046: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2047: lunarNewYearDayOfYear = 26; break; //January 26th
case 2048: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2049: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2050: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2051: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2052: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2053: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2054: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2055: lunarNewYearDayOfYear = 28; break; //January 28th
case 2056: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2057: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2058: lunarNewYearDayOfYear = 24; break; //January 24th
case 2059: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2060: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2061: lunarNewYearDayOfYear = 21; break; //January 21st
case 2062: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2063: lunarNewYearDayOfYear = 29; break; //January 29th
case 2064: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2065: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2066: lunarNewYearDayOfYear = 26; break; //January 26th
case 2067: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2068: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2069: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2070: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2071: lunarNewYearDayOfYear = 31; break; //January 31st
case 2072: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2073: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2074: lunarNewYearDayOfYear = 27; break; //January 27th
case 2075: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2076: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2077: lunarNewYearDayOfYear = 24; break; //January 24th
case 2078: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2079: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2080: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2081: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2082: lunarNewYearDayOfYear = 29; break; //January 29th
case 2083: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2084: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2085: lunarNewYearDayOfYear = 26; break; //January 26th
case 2086: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2087: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2088: lunarNewYearDayOfYear = 24; break; //January 24th
case 2089: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2090: lunarNewYearDayOfYear = 30; break; //January 30th
case 2091: lunarNewYearDayOfYear = 31+18; break; //February 18th
case 2092: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2093: lunarNewYearDayOfYear = 27; break; //January 27th
case 2094: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2095: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2096: lunarNewYearDayOfYear = 25; break; //January 25th
case 2097: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2098: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2099: lunarNewYearDayOfYear = 21; break; //January 21st
case 2100: lunarNewYearDayOfYear = 31+9; break; //February 9th
}
//celebrate for 7 days total, with Lunar New Year on the 5th day
return dayOfYear >= lunarNewYearDayOfYear-4 && dayOfYear <= lunarNewYearDayOfYear+2;
}
//has to be algorithmically computed =S
public static boolean isEaster(int year, int dayOfYear, boolean isLeapYear){
//if we're not in March or April, just skip out of all these calculations
if (dayOfYear < 59 || dayOfYear > 121) {
return false;
}
//Uses the Anonymous Gregorian Algorithm
int a = year % 19;
int b = year / 100;
int c = year % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (a*19 + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (32 + 2*e + 2*i - h - k) % 7;
int m = (a + h*11 + l*22)/451;
int n = (h + l - m*7 + 114) / 31;
int o = (h + l - m*7 + 114) % 31;
int easterDayOfYear = 0;
if (n == 3){
easterDayOfYear += 59; //march
} else {
easterDayOfYear += 90; //april
}
if (isLeapYear) {
easterDayOfYear += 1; //add an extra day to account for February 29th
}
easterDayOfYear += (o+1); //add day of month
//celebrate for 7 days total, with Easter Sunday on the 5th day
return dayOfYear >= easterDayOfYear-4 && dayOfYear <= easterDayOfYear+2;
}
}
|
11193_1 | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub. contact op met de sitebeheerder als dit vaak voor komt..";
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
| 0912293/PythonMasterRace | src/main/java/com/steen/controllers/CartController.java | 697 | // "Neem aub. contact op met de sitebeheerder als dit vaak voor komt.."; | line_comment | nl | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem<SUF>
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
|
18424_7 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 1,963 | //eerst zeker zijn dat de camera niet gebruikt wordt. | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst<SUF>
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
|
111409_1 | package com.example.idek;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;
import java.util.HashMap;
public class qrReader {
public String decoded(BinaryBitmap plaatje, HashMap<DecodeHintType,?> ddog) throws NotFoundException, FormatException, ChecksumException {
QRCodeReader qr = new QRCodeReader(); // (*・ω・)ノ ghelleu QRCodeReader
String qrResultDing; //alvast een string aanmaken waarin later de gedecodeerde zooi in gestopt wordt
try{
Result resDing = qr.decode(plaatje, ddog); //wauw. zonder medicatie is mijn beste uitleg hiervoor: "magic happens (/ ̄ー ̄)/~~☆’.・.・:★’.・.・:☆"
//aight op basis van wat je allemaal kan vragen van Result, slaat hij de ingelezen qr code in zijn geheel op.
//je zou specifieke shit kunnen opvragen afhankelijk van welke type barcode je hebt ingescand, bijv de "result points" (waarvan ik gok dat het in een qr code de grote blokken kunnen zijn?)
//en bytes en bits van wat er geencodeerd is in een qr code/aztec ding/barcode
//mensen hadden echt honger toen ze de namen hiervoor bedachten huh. "nibble, bit, byte" zolang je toetsenbord maar vrij blijft van kruimels, i guess
//alleen is dat alles niet echt relevant hier want ik wil een string terug hebben en Result kan dat ook teruggeven :D
qrResultDing = resDing.getText(); //en dat doen wij hier! geeft de string wat in de qr code stond terug en stopt dat in de string wat eerder is aangemaakt.
return qrResultDing; //< sssh ik fix het later wel als ik minder slaperig ben en shit kan lezen < VERANDER GEWOON WAT VOOR SHIT HIJ MOET TERUG GEVEN PROBLEM FIXED.
} catch (NotFoundException nf){
//aaaaaaaah oke wat doe ik met de rest. NVM I CAN'T READ/ ik kan letterlijk kiezen welke exception ik wil hebben?? < nope.
nf.printStackTrace();
} catch(FormatException fx){
fx.printStackTrace();
} catch (ChecksumException e){
e.printStackTrace();
}
return null;
}
}
| 0974201/qr-ding | app/src/main/java/com/example/idek/qrReader.java | 604 | //alvast een string aanmaken waarin later de gedecodeerde zooi in gestopt wordt | line_comment | nl | package com.example.idek;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;
import java.util.HashMap;
public class qrReader {
public String decoded(BinaryBitmap plaatje, HashMap<DecodeHintType,?> ddog) throws NotFoundException, FormatException, ChecksumException {
QRCodeReader qr = new QRCodeReader(); // (*・ω・)ノ ghelleu QRCodeReader
String qrResultDing; //alvas<SUF>
try{
Result resDing = qr.decode(plaatje, ddog); //wauw. zonder medicatie is mijn beste uitleg hiervoor: "magic happens (/ ̄ー ̄)/~~☆’.・.・:★’.・.・:☆"
//aight op basis van wat je allemaal kan vragen van Result, slaat hij de ingelezen qr code in zijn geheel op.
//je zou specifieke shit kunnen opvragen afhankelijk van welke type barcode je hebt ingescand, bijv de "result points" (waarvan ik gok dat het in een qr code de grote blokken kunnen zijn?)
//en bytes en bits van wat er geencodeerd is in een qr code/aztec ding/barcode
//mensen hadden echt honger toen ze de namen hiervoor bedachten huh. "nibble, bit, byte" zolang je toetsenbord maar vrij blijft van kruimels, i guess
//alleen is dat alles niet echt relevant hier want ik wil een string terug hebben en Result kan dat ook teruggeven :D
qrResultDing = resDing.getText(); //en dat doen wij hier! geeft de string wat in de qr code stond terug en stopt dat in de string wat eerder is aangemaakt.
return qrResultDing; //< sssh ik fix het later wel als ik minder slaperig ben en shit kan lezen < VERANDER GEWOON WAT VOOR SHIT HIJ MOET TERUG GEVEN PROBLEM FIXED.
} catch (NotFoundException nf){
//aaaaaaaah oke wat doe ik met de rest. NVM I CAN'T READ/ ik kan letterlijk kiezen welke exception ik wil hebben?? < nope.
nf.printStackTrace();
} catch(FormatException fx){
fx.printStackTrace();
} catch (ChecksumException e){
e.printStackTrace();
}
return null;
}
}
|
42150_10 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rekenmachine;
/**
*
* @author adeliae
*/
public class Telraam extends javax.swing.JFrame {
//"" achter strings gezet om te voorkomen dat null als input wordt gegeven
String eersteGetal = "";
String tweedeGetal = "";
String invoer = "";
String operatie = "";
String antwoord = "";
double uitkomst;
/**
* Creates new form Telraam
*/
public Telraam() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
invoer7 = new javax.swing.JButton();
invoer8 = new javax.swing.JButton();
invoer9 = new javax.swing.JButton();
invoer4 = new javax.swing.JButton();
invoer5 = new javax.swing.JButton();
invoer6 = new javax.swing.JButton();
invoer1 = new javax.swing.JButton();
invoer2 = new javax.swing.JButton();
invoer3 = new javax.swing.JButton();
invoer0 = new javax.swing.JButton();
invoerkomma = new javax.swing.JButton();
clearbutton = new javax.swing.JButton();
invoerplus = new javax.swing.JButton();
invoermin = new javax.swing.JButton();
invoerdelen = new javax.swing.JButton();
invoerkeer = new javax.swing.JButton();
invoermacht = new javax.swing.JButton();
uitrekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rekenmachine");
setName("telraamForm"); // NOI18N
invoer7.setText("7");
invoer7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer7ActionPerformed(evt);
}
});
invoer8.setText("8");
invoer8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer8ActionPerformed(evt);
}
});
invoer9.setText("9");
invoer9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer9ActionPerformed(evt);
}
});
invoer4.setText("4");
invoer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer4ActionPerformed(evt);
}
});
invoer5.setText("5");
invoer5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer5ActionPerformed(evt);
}
});
invoer6.setText("6");
invoer6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer6ActionPerformed(evt);
}
});
invoer1.setText("1");
invoer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer1ActionPerformed(evt);
}
});
invoer2.setText("2");
invoer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer2ActionPerformed(evt);
}
});
invoer3.setText("3");
invoer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer3ActionPerformed(evt);
}
});
invoer0.setText("0");
invoer0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer0ActionPerformed(evt);
}
});
invoerkomma.setText(".");
invoerkomma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkommaActionPerformed(evt);
}
});
clearbutton.setText("C");
clearbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearbuttonActionPerformed(evt);
}
});
invoerplus.setText("+");
invoerplus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerplusActionPerformed(evt);
}
});
invoermin.setText("-");
invoermin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerminActionPerformed(evt);
}
});
invoerdelen.setText("/");
invoerdelen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerdelenActionPerformed(evt);
}
});
invoerkeer.setText("*");
invoerkeer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkeerActionPerformed(evt);
}
});
invoermacht.setText("^");
invoermacht.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoermachtActionPerformed(evt);
}
});
uitrekenen.setText("=");
uitrekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uitrekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(invoer1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoer4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(clearbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoerplus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoermin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerdelen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkeer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerplus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoermin, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkeer, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//tijd om de knopjes een functie te geven ヾ(*・ω・)ノ゜+.゜★ィェィ☆゜+.゜ヾ(・ω・*)ノ
private void invoer7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer7ActionPerformed
String invoerGetal = jTextField1.getText() + invoer7.getText();
jTextField1.setText(invoerGetal);
//if statement gemaakt om te controleren of er al iets is ingevoerd
//zodat je niet telkens op de c knop hoeft te klikken om een nieuwe
//berekening te maken. (alleen gaat er na drie berekeningen iets mis oopsΣ(っ゚Д゚;)っ )
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 7;
} else{
invoer += 7;
}
}//GEN-LAST:event_invoer7ActionPerformed
private void invoer8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer8ActionPerformed
String invoerGetal = jTextField1.getText() + invoer8.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 8;
} else{
invoer += 8;
}
}//GEN-LAST:event_invoer8ActionPerformed
private void invoer9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer9ActionPerformed
String invoerGetal = jTextField1.getText() + invoer9.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 9;
} else{
invoer += 9;
}
}//GEN-LAST:event_invoer9ActionPerformed
private void invoer4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer4ActionPerformed
String invoerGetal = jTextField1.getText() + invoer4.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 4;
} else{
invoer += 4;
}
}//GEN-LAST:event_invoer4ActionPerformed
private void invoer5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer5ActionPerformed
String invoerGetal = jTextField1.getText() + invoer5.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 5;
} else{
invoer += 5;
}
}//GEN-LAST:event_invoer5ActionPerformed
private void invoer6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer6ActionPerformed
String invoerGetal = jTextField1.getText() + invoer6.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 6;
} else{
invoer += 6;
}
}//GEN-LAST:event_invoer6ActionPerformed
private void invoer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer1ActionPerformed
String invoerGetal = jTextField1.getText() + invoer1.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 1;
} else{
invoer += 1;
}
}//GEN-LAST:event_invoer1ActionPerformed
private void invoer2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer2ActionPerformed
String invoerGetal = jTextField1.getText() + invoer2.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 2;
} else{
invoer += 2;
}
}//GEN-LAST:event_invoer2ActionPerformed
private void invoer3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer3ActionPerformed
String invoerGetal = jTextField1.getText() + invoer3.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 3;
} else{
invoer += 3;
}
}//GEN-LAST:event_invoer3ActionPerformed
private void invoer0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer0ActionPerformed
String invoerGetal = jTextField1.getText() + invoer0.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 0;
} else{
invoer += 0;
}
}//GEN-LAST:event_invoer0ActionPerformed
private void invoerkommaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkommaActionPerformed
String invoerGetal = jTextField1.getText() + invoerkomma.getText();
jTextField1.setText(invoerGetal);
invoer += ".";
}//GEN-LAST:event_invoerkommaActionPerformed
private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearbuttonActionPerformed
jTextField1.setText("");
eersteGetal = "";
tweedeGetal = "";
invoer = "";
}//GEN-LAST:event_clearbuttonActionPerformed
private void invoerplusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerplusActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("+");
eersteGetal = invoer;
invoer = "";
operatie = "+";
}//GEN-LAST:event_invoerplusActionPerformed
private void invoerminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerminActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("-");
eersteGetal = invoer;
invoer = "";
operatie = "-";
}//GEN-LAST:event_invoerminActionPerformed
private void invoerdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerdelenActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("/");
eersteGetal = invoer;
invoer = "";
operatie = "/";
}//GEN-LAST:event_invoerdelenActionPerformed
private void invoerkeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkeerActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("*");
eersteGetal = invoer;
invoer = "";
operatie = "*";
//hhahaa ben opnieuw begonnen omdat ik de in de vorige versie
//de vermenigvuldig functie was vergeten te maken
//good job me (屮゜Д゜)屮
}//GEN-LAST:event_invoerkeerActionPerformed
private void invoermachtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoermachtActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("^");
eersteGetal = invoer;
//int uitreken = Integer.parseInt(invoer) * Integer.parseInt(invoer);
//eersteGetal = uitreken + "";
invoer = "";
operatie = "^";
//System.out.println(eersteGetal);
//eersteGetal = uitkomst + "";
//jTextField1.setText(eersteGetal);
}//GEN-LAST:event_invoermachtActionPerformed
private void uitrekenenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uitrekenenActionPerformed
//TO INFINITY AND BEYOOOOOOOOOOOOOOOOOOOOND ゚+.(ノ。'▽')ノ*.オオォォ☆゚・:*☆
//hier wordt alles berekend
tweedeGetal = invoer;
//System.out.println(eersteGetal);
//System.out.println(tweedeGetal);
if(eersteGetal!= "" && tweedeGetal != ""){
if(operatie == "+" ){
uitkomst = Double.parseDouble(eersteGetal) + Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "-"){
uitkomst = Double.parseDouble(eersteGetal) - Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "/"){
uitkomst = Double.parseDouble(eersteGetal) / Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "*"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "^"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(eersteGetal); //heb dit gebruikt ipv math.pow
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
}
}
}//GEN-LAST:event_uitrekenenActionPerformed
/* het is mij niet echt gelukt om een manier te vinden om het resultaat
* van het machtsverheffen te laten weergeven, aangezien mijn rekenmachine
* eerst twee inputs wilt hebben.
* heb geprobeerd om het op een andere manier te doen (zie de comments in
* invoermacht) maar dat lukte ook niet echt. het kan het in iedergeval wel
* uitrekenen.
*/
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Telraam().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearbutton;
private javax.swing.JButton invoer0;
private javax.swing.JButton invoer1;
private javax.swing.JButton invoer2;
private javax.swing.JButton invoer3;
private javax.swing.JButton invoer4;
private javax.swing.JButton invoer5;
private javax.swing.JButton invoer6;
private javax.swing.JButton invoer7;
private javax.swing.JButton invoer8;
private javax.swing.JButton invoer9;
private javax.swing.JButton invoerdelen;
private javax.swing.JButton invoerkeer;
private javax.swing.JButton invoerkomma;
private javax.swing.JButton invoermacht;
private javax.swing.JButton invoermin;
private javax.swing.JButton invoerplus;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton uitrekenen;
// End of variables declaration//GEN-END:variables
}
| 0974201/rekenmachine2 | src/rekenmachine/Telraam.java | 6,708 | //if statement gemaakt om te controleren of er al iets is ingevoerd | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rekenmachine;
/**
*
* @author adeliae
*/
public class Telraam extends javax.swing.JFrame {
//"" achter strings gezet om te voorkomen dat null als input wordt gegeven
String eersteGetal = "";
String tweedeGetal = "";
String invoer = "";
String operatie = "";
String antwoord = "";
double uitkomst;
/**
* Creates new form Telraam
*/
public Telraam() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
invoer7 = new javax.swing.JButton();
invoer8 = new javax.swing.JButton();
invoer9 = new javax.swing.JButton();
invoer4 = new javax.swing.JButton();
invoer5 = new javax.swing.JButton();
invoer6 = new javax.swing.JButton();
invoer1 = new javax.swing.JButton();
invoer2 = new javax.swing.JButton();
invoer3 = new javax.swing.JButton();
invoer0 = new javax.swing.JButton();
invoerkomma = new javax.swing.JButton();
clearbutton = new javax.swing.JButton();
invoerplus = new javax.swing.JButton();
invoermin = new javax.swing.JButton();
invoerdelen = new javax.swing.JButton();
invoerkeer = new javax.swing.JButton();
invoermacht = new javax.swing.JButton();
uitrekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rekenmachine");
setName("telraamForm"); // NOI18N
invoer7.setText("7");
invoer7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer7ActionPerformed(evt);
}
});
invoer8.setText("8");
invoer8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer8ActionPerformed(evt);
}
});
invoer9.setText("9");
invoer9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer9ActionPerformed(evt);
}
});
invoer4.setText("4");
invoer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer4ActionPerformed(evt);
}
});
invoer5.setText("5");
invoer5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer5ActionPerformed(evt);
}
});
invoer6.setText("6");
invoer6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer6ActionPerformed(evt);
}
});
invoer1.setText("1");
invoer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer1ActionPerformed(evt);
}
});
invoer2.setText("2");
invoer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer2ActionPerformed(evt);
}
});
invoer3.setText("3");
invoer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer3ActionPerformed(evt);
}
});
invoer0.setText("0");
invoer0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer0ActionPerformed(evt);
}
});
invoerkomma.setText(".");
invoerkomma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkommaActionPerformed(evt);
}
});
clearbutton.setText("C");
clearbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearbuttonActionPerformed(evt);
}
});
invoerplus.setText("+");
invoerplus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerplusActionPerformed(evt);
}
});
invoermin.setText("-");
invoermin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerminActionPerformed(evt);
}
});
invoerdelen.setText("/");
invoerdelen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerdelenActionPerformed(evt);
}
});
invoerkeer.setText("*");
invoerkeer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkeerActionPerformed(evt);
}
});
invoermacht.setText("^");
invoermacht.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoermachtActionPerformed(evt);
}
});
uitrekenen.setText("=");
uitrekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uitrekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(invoer1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoer4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(clearbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoerplus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoermin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerdelen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkeer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerplus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoermin, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkeer, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//tijd om de knopjes een functie te geven ヾ(*・ω・)ノ゜+.゜★ィェィ☆゜+.゜ヾ(・ω・*)ノ
private void invoer7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer7ActionPerformed
String invoerGetal = jTextField1.getText() + invoer7.getText();
jTextField1.setText(invoerGetal);
//if st<SUF>
//zodat je niet telkens op de c knop hoeft te klikken om een nieuwe
//berekening te maken. (alleen gaat er na drie berekeningen iets mis oopsΣ(っ゚Д゚;)っ )
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 7;
} else{
invoer += 7;
}
}//GEN-LAST:event_invoer7ActionPerformed
private void invoer8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer8ActionPerformed
String invoerGetal = jTextField1.getText() + invoer8.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 8;
} else{
invoer += 8;
}
}//GEN-LAST:event_invoer8ActionPerformed
private void invoer9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer9ActionPerformed
String invoerGetal = jTextField1.getText() + invoer9.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 9;
} else{
invoer += 9;
}
}//GEN-LAST:event_invoer9ActionPerformed
private void invoer4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer4ActionPerformed
String invoerGetal = jTextField1.getText() + invoer4.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 4;
} else{
invoer += 4;
}
}//GEN-LAST:event_invoer4ActionPerformed
private void invoer5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer5ActionPerformed
String invoerGetal = jTextField1.getText() + invoer5.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 5;
} else{
invoer += 5;
}
}//GEN-LAST:event_invoer5ActionPerformed
private void invoer6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer6ActionPerformed
String invoerGetal = jTextField1.getText() + invoer6.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 6;
} else{
invoer += 6;
}
}//GEN-LAST:event_invoer6ActionPerformed
private void invoer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer1ActionPerformed
String invoerGetal = jTextField1.getText() + invoer1.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 1;
} else{
invoer += 1;
}
}//GEN-LAST:event_invoer1ActionPerformed
private void invoer2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer2ActionPerformed
String invoerGetal = jTextField1.getText() + invoer2.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 2;
} else{
invoer += 2;
}
}//GEN-LAST:event_invoer2ActionPerformed
private void invoer3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer3ActionPerformed
String invoerGetal = jTextField1.getText() + invoer3.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 3;
} else{
invoer += 3;
}
}//GEN-LAST:event_invoer3ActionPerformed
private void invoer0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer0ActionPerformed
String invoerGetal = jTextField1.getText() + invoer0.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 0;
} else{
invoer += 0;
}
}//GEN-LAST:event_invoer0ActionPerformed
private void invoerkommaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkommaActionPerformed
String invoerGetal = jTextField1.getText() + invoerkomma.getText();
jTextField1.setText(invoerGetal);
invoer += ".";
}//GEN-LAST:event_invoerkommaActionPerformed
private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearbuttonActionPerformed
jTextField1.setText("");
eersteGetal = "";
tweedeGetal = "";
invoer = "";
}//GEN-LAST:event_clearbuttonActionPerformed
private void invoerplusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerplusActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("+");
eersteGetal = invoer;
invoer = "";
operatie = "+";
}//GEN-LAST:event_invoerplusActionPerformed
private void invoerminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerminActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("-");
eersteGetal = invoer;
invoer = "";
operatie = "-";
}//GEN-LAST:event_invoerminActionPerformed
private void invoerdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerdelenActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("/");
eersteGetal = invoer;
invoer = "";
operatie = "/";
}//GEN-LAST:event_invoerdelenActionPerformed
private void invoerkeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkeerActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("*");
eersteGetal = invoer;
invoer = "";
operatie = "*";
//hhahaa ben opnieuw begonnen omdat ik de in de vorige versie
//de vermenigvuldig functie was vergeten te maken
//good job me (屮゜Д゜)屮
}//GEN-LAST:event_invoerkeerActionPerformed
private void invoermachtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoermachtActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("^");
eersteGetal = invoer;
//int uitreken = Integer.parseInt(invoer) * Integer.parseInt(invoer);
//eersteGetal = uitreken + "";
invoer = "";
operatie = "^";
//System.out.println(eersteGetal);
//eersteGetal = uitkomst + "";
//jTextField1.setText(eersteGetal);
}//GEN-LAST:event_invoermachtActionPerformed
private void uitrekenenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uitrekenenActionPerformed
//TO INFINITY AND BEYOOOOOOOOOOOOOOOOOOOOND ゚+.(ノ。'▽')ノ*.オオォォ☆゚・:*☆
//hier wordt alles berekend
tweedeGetal = invoer;
//System.out.println(eersteGetal);
//System.out.println(tweedeGetal);
if(eersteGetal!= "" && tweedeGetal != ""){
if(operatie == "+" ){
uitkomst = Double.parseDouble(eersteGetal) + Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "-"){
uitkomst = Double.parseDouble(eersteGetal) - Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "/"){
uitkomst = Double.parseDouble(eersteGetal) / Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "*"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "^"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(eersteGetal); //heb dit gebruikt ipv math.pow
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
}
}
}//GEN-LAST:event_uitrekenenActionPerformed
/* het is mij niet echt gelukt om een manier te vinden om het resultaat
* van het machtsverheffen te laten weergeven, aangezien mijn rekenmachine
* eerst twee inputs wilt hebben.
* heb geprobeerd om het op een andere manier te doen (zie de comments in
* invoermacht) maar dat lukte ook niet echt. het kan het in iedergeval wel
* uitrekenen.
*/
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Telraam().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearbutton;
private javax.swing.JButton invoer0;
private javax.swing.JButton invoer1;
private javax.swing.JButton invoer2;
private javax.swing.JButton invoer3;
private javax.swing.JButton invoer4;
private javax.swing.JButton invoer5;
private javax.swing.JButton invoer6;
private javax.swing.JButton invoer7;
private javax.swing.JButton invoer8;
private javax.swing.JButton invoer9;
private javax.swing.JButton invoerdelen;
private javax.swing.JButton invoerkeer;
private javax.swing.JButton invoerkomma;
private javax.swing.JButton invoermacht;
private javax.swing.JButton invoermin;
private javax.swing.JButton invoerplus;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton uitrekenen;
// End of variables declaration//GEN-END:variables
}
|
87789_1 |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} | 0NightBot0/DevDatabase | assignment 2/MongoDB/src/mongodbtest/MongoDBTest.java | 1,099 | // Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt | line_comment | nl |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is<SUF>
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} |
158349_78 | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
| 0XDE57/SpaceProject | core/src/com/spaceproject/math/Physics.java | 6,603 | //5772K = 502nm = 597 THz = green light | line_comment | nl | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K<SUF>
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
|
194699_31 | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
| 0dentitaet/gdp | gdp/IntSet.java | 2,008 | /**
* IntSet Mengen-Iterator
*/ | block_comment | nl | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet<SUF>*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
|
13786_15 | package gameapplication.model;
import gameapplication.model.chess.Board;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.pieces.Pawn;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.List;
/**
* The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the
* last spot clicked. It also has a list of moves, which are used to store the moves made
*/
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public class MoveManager {
// This is creating a list of spots, which is used to store the last spot clicked.
private List<Spot> spots = new ArrayList<>();
// This is creating a list of strings, which is used to store the moves made.
private List<String> movesList;
// Creating a reference to the board.
private Board board;
// This is creating a new MoveManager object, and initializing the board and movesList.
public MoveManager(Board board) {
this.board = board;
movesList = new ArrayList<>();
}
/**
* If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots
* list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is
* a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public void addMove(int column, int row) {
// Getting the piece from the spot that was clicked on.
Piece clickedOnPiece = board.getPieceFromSpot(column, row);
// This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked
// yet.
if (spots.isEmpty()) {
// Kijk of er op niks geklicked werd, zoja doe niks
if (clickedOnPiece == null) return;
// als er op een andere piece gecklicked werd, doe ook niks.
if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return;
// This is adding the spot that was clicked on to the spots list.
spots.add(new Spot(column, row));
return;
}
// The above code is checking if the piece that was clicked on is the same color as the last piece that was moved.
// If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it
// will add the spot to the list of spots.
if (spots.size() == 1) {
Spot firstSpot = spots.get(0);
Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow());
Piece currentPiece = board.getPieceFromSpot(column, row);
if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) {
return;
}
//Als huidige geklickde piece heeft dezelfde kleur als de vorige piece,
if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) {
// verwijder de vorige spot,
spots.remove(0);
//en maak een recursieve oproep naar de addMove methode
addMove(column, row);
} else {
//Als move niet mogelijk is
try {
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
} catch (NullPointerException npe) {
pieceFromSpot.setBoard(getBoard());
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
}
//^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd.
//Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is.
for (Spot[] validMove : pieceFromSpot.validMoves(board)) {
for (Spot spot : validMove) {
if (spot != null && spot.getColumn() == column && spot.getRow() == row) {
//zoja, add de 2de spot naar de lijst, en roep de make move methode op.
//Check if next move will cause check, or disable the check.
if (testMove(new Spot(column, row), null)) {
return;
}
//if not in a checked state, or testMove return true
spots.add(new Spot(column, row));
//prepare next turn
makeMove();
}
}
}
}
}
}
//move the piece and prepare next turn
/**
* This function moves a piece from one spot to another
*/
public void makeMove() {
Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow());
// Actually move the piece
piece.moveToSpot(board, spots.get(1));
// This is checking if the piece is a pawn. If it is, it will check if it is promotable.
if (piece.getPieceType() == Piecetype.PAWN) {
Pawn pawn = (Pawn) piece;
pawn.checkIfPromotionAvailable();
}
// This is clearing the list of spots, and switching the player.
addMoveToList();
spots.clear();
board.switchPlayer();
// Checking if the current player is in check. If it is, it will check if the player is in checkmate.
board.checkForCheck();
// Switching the player.
board.nextTurn();
}
//Method to check if the next move during check, will evade the check
/**
* This function checks if the move is valid by checking if the king is in check after the move
*
* @param secondSpot the spot where the piece is moving to
* @param firstSpot the spot where the piece is currently located
* @return A boolean value.
*/
public boolean testMove(Spot secondSpot, Spot firstSpot) {
//second parameter to check for checkmate, only available if called from the board
Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0);
//create a reference to the old board
Board tempBoard = board;
//create a copy of the old piece, in case there is one on the second spot
Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()];
// get the piece from the first spot
Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow());
//if there was a piece on the second spot, remove it
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
}
// remove the piece from the first spot
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null;
// set the piece from the first spot in the second spot
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece;
//check if after doing this, the check is still there
if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) {
//if yes, put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return true;
}
//if not, also put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return false;
}
/**
* Add the move to the list of moves
*/
public void addMoveToList() {
movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName()));
}
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param spotString a string that represents a list of spots.
* @return A list of spots.
*/
public List<Spot> getSpotFromString(String spotString) {
String[] twoSpots = spotString.split(":");
List<Spot> spot = new ArrayList<>();
if (twoSpots.length == 0) {
return null;
}
for (String singleSpot : twoSpots) {
String[] columnAndRow = singleSpot.split("\\.");
try {
spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1])));
} catch (Exception e) {
return null;
}
}
return spot;
}
/**
* Returns the board
*
* @return The board object.
*/
public Board getBoard() {
return board;
}
public List<String> getMovesList() {
return movesList;
}
public List<Spot> getMoves() {
return spots;
}
}
| 0xBienCuit/ChessGame | src/gameapplication/model/MoveManager.java | 2,449 | //Als huidige geklickde piece heeft dezelfde kleur als de vorige piece, | line_comment | nl | package gameapplication.model;
import gameapplication.model.chess.Board;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.pieces.Pawn;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.List;
/**
* The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the
* last spot clicked. It also has a list of moves, which are used to store the moves made
*/
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public class MoveManager {
// This is creating a list of spots, which is used to store the last spot clicked.
private List<Spot> spots = new ArrayList<>();
// This is creating a list of strings, which is used to store the moves made.
private List<String> movesList;
// Creating a reference to the board.
private Board board;
// This is creating a new MoveManager object, and initializing the board and movesList.
public MoveManager(Board board) {
this.board = board;
movesList = new ArrayList<>();
}
/**
* If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots
* list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is
* a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public void addMove(int column, int row) {
// Getting the piece from the spot that was clicked on.
Piece clickedOnPiece = board.getPieceFromSpot(column, row);
// This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked
// yet.
if (spots.isEmpty()) {
// Kijk of er op niks geklicked werd, zoja doe niks
if (clickedOnPiece == null) return;
// als er op een andere piece gecklicked werd, doe ook niks.
if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return;
// This is adding the spot that was clicked on to the spots list.
spots.add(new Spot(column, row));
return;
}
// The above code is checking if the piece that was clicked on is the same color as the last piece that was moved.
// If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it
// will add the spot to the list of spots.
if (spots.size() == 1) {
Spot firstSpot = spots.get(0);
Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow());
Piece currentPiece = board.getPieceFromSpot(column, row);
if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) {
return;
}
//Als h<SUF>
if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) {
// verwijder de vorige spot,
spots.remove(0);
//en maak een recursieve oproep naar de addMove methode
addMove(column, row);
} else {
//Als move niet mogelijk is
try {
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
} catch (NullPointerException npe) {
pieceFromSpot.setBoard(getBoard());
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
}
//^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd.
//Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is.
for (Spot[] validMove : pieceFromSpot.validMoves(board)) {
for (Spot spot : validMove) {
if (spot != null && spot.getColumn() == column && spot.getRow() == row) {
//zoja, add de 2de spot naar de lijst, en roep de make move methode op.
//Check if next move will cause check, or disable the check.
if (testMove(new Spot(column, row), null)) {
return;
}
//if not in a checked state, or testMove return true
spots.add(new Spot(column, row));
//prepare next turn
makeMove();
}
}
}
}
}
}
//move the piece and prepare next turn
/**
* This function moves a piece from one spot to another
*/
public void makeMove() {
Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow());
// Actually move the piece
piece.moveToSpot(board, spots.get(1));
// This is checking if the piece is a pawn. If it is, it will check if it is promotable.
if (piece.getPieceType() == Piecetype.PAWN) {
Pawn pawn = (Pawn) piece;
pawn.checkIfPromotionAvailable();
}
// This is clearing the list of spots, and switching the player.
addMoveToList();
spots.clear();
board.switchPlayer();
// Checking if the current player is in check. If it is, it will check if the player is in checkmate.
board.checkForCheck();
// Switching the player.
board.nextTurn();
}
//Method to check if the next move during check, will evade the check
/**
* This function checks if the move is valid by checking if the king is in check after the move
*
* @param secondSpot the spot where the piece is moving to
* @param firstSpot the spot where the piece is currently located
* @return A boolean value.
*/
public boolean testMove(Spot secondSpot, Spot firstSpot) {
//second parameter to check for checkmate, only available if called from the board
Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0);
//create a reference to the old board
Board tempBoard = board;
//create a copy of the old piece, in case there is one on the second spot
Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()];
// get the piece from the first spot
Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow());
//if there was a piece on the second spot, remove it
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
}
// remove the piece from the first spot
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null;
// set the piece from the first spot in the second spot
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece;
//check if after doing this, the check is still there
if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) {
//if yes, put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return true;
}
//if not, also put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return false;
}
/**
* Add the move to the list of moves
*/
public void addMoveToList() {
movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName()));
}
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param spotString a string that represents a list of spots.
* @return A list of spots.
*/
public List<Spot> getSpotFromString(String spotString) {
String[] twoSpots = spotString.split(":");
List<Spot> spot = new ArrayList<>();
if (twoSpots.length == 0) {
return null;
}
for (String singleSpot : twoSpots) {
String[] columnAndRow = singleSpot.split("\\.");
try {
spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1])));
} catch (Exception e) {
return null;
}
}
return spot;
}
/**
* Returns the board
*
* @return The board object.
*/
public Board getBoard() {
return board;
}
public List<String> getMovesList() {
return movesList;
}
public List<Spot> getMoves() {
return spots;
}
}
|
183866_30 | "/* -*-mode:java; c-basic-offset:2; -*- */\n/*\nCopyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. (...TRUNCATED) | 0xRustlang/keepass2android | src/java/JavaFileStorage/app/src/main/java/com/jcraft/jsch/jzlib/Tree.java | 7,044 | // bit length | line_comment | nl | "/* -*-mode:java; c-basic-offset:2; -*- */\n/*\nCopyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. (...TRUNCATED) |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4