-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava1.java
More file actions
executable file
·133 lines (117 loc) · 2.18 KB
/
Java1.java
File metadata and controls
executable file
·133 lines (117 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package com.example;
public class Lab {
/*
* 1. Cast from double to int
*
* labels:[primitives, casting]
*
* f(0.0) = 0
* f(3.1) = 3
*/
public static int castToInt(double n) {
return (int) n;
}
/*
* 2. Cast from short to byte
*
* labels:[primitives, casting]
*
* f(2) = 2
* f(128) = -128
*/
public static byte castToByte(short n) {
return (byte) n;
}
/*
* 3. Division
*
* labels:[operators, exceptions, control statements]
*
* f(10,2) = 5.0
* f(3,2) = 1.5
* f(1,0) = throw IllegalArgumentException
*/
public static double divide(double operandOne, double operandTwo) throws IllegalArgumentException {
if (operandTwo ==0.0){
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
return operandOne/operandTwo;
}
/*
* 4. Even
*
* labels:[operators, control statements]
*
* f(2) = true
* f(3) = false
*/
public static boolean isEven(int n) {
return (n%2==0);
}
/*
* 5. All even
*
* labels:[operators, arrays, control statements]
*
* f([2]) = true
* f([2,4,6,8,10]) = true
*
* f([3]) = false
* f([2,4,6,8,11]) = false
*/
public static boolean isAllEven(int[] array) {
for (int i = 0; i<array.length; i++){
if (array[i]%2 == 1) {
return false;
}
}
return true;
}
/*
* 6. Average
*
* labels:[arrays, operators, control statements, exceptions]
*
* f([2]) = 2.0
* f([2,3]) = 2.5
* f(null) = throw IllegalArgumentException
*/
public static double average(int[] array) throws IllegalArgumentException{
int sum = 0;
try {
for (int i = 0; i< array.length; i++) {
sum += array[i] ;
}
}
catch (NullPointerException e) {
IllegalArgumentException f = new IllegalArgumentException() ;
throw f;
}
if (array.length == 0){
return 0.0;
}
else{
return (double)sum/(double)array.length;
}
}
/*
* 7. Palindrome
*
* labels:[strings]
*
* f("a") = true
* f("aba") = true
* f("abba") = true
*
* f("ab") = false
*/
public static boolean isPalindrome(String str) {
for (int i = 0; i<str.length(); i++){
if (str.charAt(i) != str.charAt(str.length()-i-1)) {
return false;
}
}
return true;
}
}