0 ratings 0% found this document useful (0 votes) 17 views 16 pages Assignment 7
The document contains Java code for various applications, including a password generator, a snake game, a simple bar chart, and an online survey system. It demonstrates methods for generating random passwords, encrypting and decrypting data using AES, handling user input for a survey, and rendering graphics for a game. Overall, it showcases different programming techniques and functionalities in Java.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save assignment 7 For Later Ve
bytel] decodeabytes = Bare64.getDecoder() decode encryptedPassuord);
‘cipher. doFinal (decodedtytes);
bytel) decryptactyte
return new String(decryptecbytes);
)
public stotie Seerettey generateseerettey() throws exception (
KeyGenerstor KeyGenerstor = Keycenerator-getinstance(
KeyGenerator.inst(128); // AES key size
return KeyGenerator-goneratexey();
)
public static void main(string{] args)
ty t
U/ Generate 2 randon passions
String passnord = generatePessvord(12); // Generete a 12-cheracter password
systen.ovt-prantin( "Gene
11 Generate 2 secret key for encryption
Seeretiey seeretkey = generatesecrethey()5
11 encrypt the pacenord
Systen.out printin("tncrypted Password:
11 Decrypt the pessverd
Systen-out.printn("Decryptea Password
) eaten (exception e) {
cvprineseacktrece();
EP typereretovearch SIM
nord = encryptPassword(passvord, 5
deeryptPassuordencryptedPassword, secretkey);
H®C@w POO Im
rarer)
(Celebi ed catineraeeoeotiecr ten
ee Rea ees
Ne eee re
Jsars\BA8Y\Desktop\jave prograns>java Pesswordanerator
etn
Lecter
eae nae et
Psche .9GGua 7neat - Notepad
Epo view Help
public class Passwordcenerator {
11 Method to generate a random password
public static String generatePassword(int Length) {
fino] String characters = "ABCDEFGHIIKLIMOPQRSTUVUKYZabedefghijkImnopqrstuvnxy201234567891 GWSX°8"(
SecureRanéon randos = new Securetandon();
StringBuilder password = new StringBuilder();
for (int i = 6; i < length; itt) {
int index © randon.nextint(characters.Length()) ;
password. eppend( characters. charat(index));
y
return possword.tostring();
)
public static String encryptPassword(String password, SecretKey secretkey) throus Exception {
Cipher cipher = Cipher.getinstance("AES") ;
cipher init(Cipher.ENCRYPT_HOOE, secretKey);
bytel) encryptedtytes = cipher. doFinal (passiord. getBytes());
return BaseGd.getEncoder().encodeTostring(encryptedBytes) ;
,
11 Method to decrypt 9 password
public static String decryptPassuord(String encryptedPassuord, Secretkey secretKey) throws Exception (
Cipher cipher = Cipher.getInstance("AES");
cipher. init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedaytes = baseéd.getDecoder().decode(encryptedPassuord) ;
byte[] decryptedBytes = cipher.doFinal (decodedBytes) ;
return new String(decryptedBytes);
}
ublic static SecretKey generatesecretkey() throws Exception (
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // AES key size
return keyGenerator.generatekey();
cn s0.colt
HEP ype here to search mit @@ueerecasn
<1 Oli:
1 OMyNAVs view Helo
inbort javax.swing.*;
inport Java.aut.*;
import Javaaut.event.*;
Inport Java-util.arraylist;
import Java-util Randos;
public class SnakeGane extends JPanel inplenents ActionListener, KeyListener {
Fee gee esta
es
Cenc?
private final ine 80x SIZE = 25; // Size of each grid box
private final int GRIO_WiOTH = 20;
private Final int GRIOLHEIGHT = 205
private final int SCREEN MIOTH = GRID_WIDTH * Box SIZE;
private #inal int SCREEN HEIGHT = GAID_HEIGHT * BOX SIZE;
private final ArrayListePoint> snake = new ArrayListo>()5
private Point food; Soret
char direction =
boolean ganeover
85 1 Us Up, 0: Down, L: Left, R: Right
false;
sre came
private
private
final Tiner einer
‘inal Random random
new Téner(150, this);
ew Random(};
public Snakecane() {
setPreferredSize(new Dinension(SCREEN_MIOTH, SCREEH_HETGHT));
setBackeround(Coler- BLACK);
setFocusable( true);
fddkeyListener(this);
snitializecone();
einer. start);
?
11 Initialize the snake ond food
private voia snitielizesane() {
snake.clear()3
ah @ @ w eons
BE Typehere to search
ee end
er Coo a ccs
(Sim 7) MMS ESAecla «Notepad
‘omat View Help
Private void initializecame() {
snake.clear()3
snake.add(new Point(S, 5)); // Snake starting position
spawnFood();
direction = 'R';
gameOver = false;
}
// Spawn food at a random position
private void spawnFood() {
int x = random.nextInt (6RIO_WIOTH);
int y = random.nextInt (GRID_HEIGHT) ;
food = new Point(x, y)5
1/ Ensure food does not spann on the snake
while (snake.contains(food)) {
x = random.nextInt (GRID_WIDTH) ;
y = random.nextInt (GRIO_HETGHT) ;
food = new Point(x, y);
t
Goverride
public void actionPerformed(AactionEvent e) {
if (IgameOver) {
movesnake();
checkCollision();
repaint();
?
// Pove the snake based on the current direction
private void movesnake() {
Point head = snake.get(0);
in7.¢
Ho ®@@euemogocwarn ‘
8 © type here to search * SeNotepad
View Help
Nove the snake based on the current direction
private void movesnake() {
Point head = snake.get(@);
Point newHead = switch (direction) {
case 'U' -> new Point(head.x, head.y - 1);
case 'D' -> new Point(head.x, head.y + 1);
case 'L' -> new Point(head.x - 1, head.y);
case 'R’ -> new Point(head.x +1, head.y);
default -> head;
%
1 Add the new head position
snake.add(®, neuHead);
JI Check if the snake eats food
Af (newHead.equals(food)) {
spaunFood();
yelse ¢ 2
// Remove the tail if no food is eaten
snake.renove(snake.size() - i);
}
HI Check for collisions
private void checkCollision() {
Point head = snake.get(0);
11 Check if the snake hits the walls
if (head.x < @ || head.y < @ || head.x
gameOver = true;
y
GRIO_WIDTH || head.y
RID_HEIGHT) {
1] Check if the snake hits itself
for (int i = 2; i < snake.size(); i4+) {
Ln7.col23
Ler
HE | © Type here to searchwo
Qoverride
protected void paintConponent (Graphics g) {
super.paintComponent(e);
11 raw the snake
g-setcolor(coler. GREEN);
for (Point point : snake) {
g.fillRect(point.x * GOK SIZE, polnt.y * 8OX.SIZE, SOX SIZE, 60x SIZE);
x
11 Brau the food
g-setcolor(Color.RED)
E.FildRect(Food.x * 80x SIZE, food.y * SOK SIZE, SOX SIZE, BOX SIZE);
11 Draw ane over message
LF (ganeover) {
i SetColor(color HITE);
-setFont (new Font ("Ar
String message
» Font.8010, 28);
"Gane Over! Press R to Restart";
g.dransteing(nessage, (SCREEN,WIOTA - g.getFontNetries()-stringhidth(nessage)) / 2, SCREEN HETGHT / 2);
>
y
override
public void keyPressed(KeyEvent e) {
Af (Iganeover) {
sultch (e.getkeyCode()) ¢
‘case KeyEvent.Vk_UP => {
a (direction I="
?
ase KeyEvent.vk_OOHN => {
af (direction I= "U') direction
) direction = ‘U's
BED typehere to search
| ar
Window (
@0@xneO6 3a Scns MEGNotepad
t View Matp
case KeyEvent.VK_DONN ~> {
if (direction |= ‘U') direction =
+
case KeyEvent.VK_LEFT -> {
if (direction != 'R') direction =
}
case KeyEvent.VK_RIGHT -> {
if (direction != 'L') direction =
?
7/ Restart the game
if (gameOver 8 e.getKeyCode()
initializecame();
+
KeyEvent.VK_R) {
?
eoverride
public void keyTyped(KeyEvent e) {}
eoverride Fi
public void keyReleased(Keyevent e) {}
public static void main(String[] args) {
3Frame frame = new JFrame("Snake Gane");
SnakeGame game = new SnakeGame();
frame.add(game)
frame.pack(
frame. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
‘frame. setVisible(true);
tn7.€o
HP ypereetosecn | ol Om & O67 m 3c Ropers
6% Javan. swing"; piaeeas
mort 3avavait.*5
volte class sinplesarchart extends 2anel (
private int[] data = (50, 72, 30, 0, 60}; // Example data
rivete String{] lebels + (k", "e","“c*,'"0", "E°}; // Labels for bars
override
protected void paintcongenent(Graphics @)
super paintConponent(e)
Graphies20 gad» (Graphics2d) g;
int wigth = gewutsth()s
dnt height » getieight();
fnt barildth = width / date.tength; // Width of each bar
Ant waxBarteignt = height - 503" // Reserve space for labels
11 Find the eaximum dota value for scaling
for (ine value ? date) (
AF (value > moxdsta) {
‘nexDats = valve,
?
)
11 rau bers
for (int £ = 0; 4 data.teneth; ist) (
ne barhight = (int) ((dat
i * baruiath;
height ~ bartieignt - 30;
[41 / (dowte) naxoata) * maxBariieight);
11 rau bar
£224. SetColor(color.8LUE);- wotepaa
s
he
jt maxData = @
for (int value : data) {
if (value > maxData) {
2
}
maxData = value;
// Draw bars
for (int i = 0; i < data.length; i++) {
int barHeight = (int) ((data[i] / (double) maxData) * maxBarHeight) ;
int x = i * barWidth;
int y = height - barHeight - 30;
// Draw bar
g2d.setColor(Color.BLUE) ;
e2d.fillRect(x + 10, y, barWidth - 20, barHeight);
// Draw label
2d. setColor(Color.BLACK);
g2d.drawString(labels[i], x + barWidth / 2 - 10, height - 10);
+
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Bar Chart”
SimpleBerChart chart = new SimpleBarChart();
frame.
frame.
frame.
Frame.
EE Type here to search
add(chart);
setSize(508, 408);
setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE) ;
setVisible(true);
‘Io @@nwaoses.
public class Onlinesurveysysten {
public static void main(String[] ares) {
Scanner scanner = new Scanner(Systen. in);
/] questions for the survey
String{] questions = {
Hot satisfied are you with our service? (1-5),
How likely are you to reconmend us to others? (1-5)",
How user-friendly is our platform? (1-5)
h
// heray to store responses
int[]f] responses © new int{questions.2ength)[5]; // § options (1-5)
// conduct the survey
‘System.out.printin("Welcone to the Online Survey!");,
System_out print("Enter the nunber of participants:
int participants « scanner.nextint();
Seanner.nextLine(); // Consume the newline
for (int p = 1; p <= participants; pre) {
Syatem.out.printin("\nParticipant "+ p+
for (int q= 0; 4 < questions. length; ae+) {
System. out printin(questions[q]);,
ine answer = ©
ds
11 validate input
nite (true)
ary
answer = Integer. parseZnt(scannernextLine())s
Sf (answer d© 18 answer <= 5) {
break
ry A/a @ enue
P wpe here 10 search
i Command Prompt jive OnlieSurveySytem
ar RTE)
(Glicenten armoire roceatons
BAe ea ee ene red
Oe ene eee one ee
fC ag een ane ees
A re ea ons
QNeap tenon ena
esiearn ste nts
eroeape ieee beset eas
atten
ict o aor ece)
Bw Hae
eooja®// Validate input
while (true) {
try {|
answer = Integer.parseInt(scanner.nextLine());
if (answer >= 1 8& answer <= 5) {
break;
} else {
System.out.println("Please enter a number between 1 and 5.");
+
} catch (NumberFormatexception e) {
System.out.printIn("Invalid input. Please enter a number between 1 and 5.");
+
// Record response
responses[q][answer - 1]++5
7
?
// Display survey results
System.out.printIn("\nSurvey Results:");
for (int q = @; q < questions.length; g++) {
System.out.printin("\n" + questions[q]);
for (int option = @; option < 5; option++) {
System.out.print1n((option + 1) +
}
}
+ responses[q][option] + * responses");
scanner.close();
}
§5 | type here to searchQa, Code ow Sueeve enllme sytem +
Sport — Bava udil Scammer’,
public. clots publve survey T
public sft veid main (shy ongicD) £
Leammn ce = new Caanmur(Sycton tn)s,
CHG) ection, =F" Hao cdtefted ave you votth woe cor Db
vecommed Fo othesy [1s e
“uno te ocr pheclfeorng UCD" 5 | e
“oP pO OPoodoadWHIT} yetpmnse amo Sot Lyrccatton- ler) C5
S-0.) (Saeltome ch the online feng x,
Lop Ls Ede me portveapesta:”
a)
9.7 eda mumbee bd Ig ef
a catch (Numbufarmed Exception e)f
cp LE Savelid, please endiv A number bf Laud 6.")% ty
responte[p | [amvon 145 YY ee
Sop (\n Suevey Results, ‘t
fe xt q204 pequettionbegths yt) §
S09 UM" x qnectionlyD) 5
fic Liat option 204 optionzes, optonstt) 7
cop Lopsion td) +2“ ereapomee lye tied) 4" cretpones" \¢
4
—_— cloce LD 5
i :
}
@ Tan Code _o% picdninl ak pasion s 4 eta
Gemapec Sava. suing. © 5
tmprdt Sava. ant **
‘ public olaey Reco encbends Jpn £
,
,
> Sat pocticipawk 2 Konner. next Sud C4
> Sommer, nedtlines,
> fy ind pe pesperticipada pets
> Sop Un pordicipad ape” s*) oe
> for Lint 4, -0) pepestion, leg tle, roe
a PF sop (query):
> Tk aaswu=O;
While ruc) g
3 ary a
3 am = Tachegere porsedad Samenre nesbLiwel 0) 5
3 Flansour > a1 fg amon <2 5) 2
i breaks
3 q ete b
S
Ss
S
RRR eee ee
UR)per IM4C) data = Pee, 40, 30, QG0, bv 6
pws Shige] pablo 2 peavia’, "es Sp" ete
protected void pind Compomut (Graphics @') §
Suyer. pabudComponead (a De :
GrnplterD poe CGrrophics2) vv
int welt © gethtttthios
int height > ae Heaght 0)", ;
int barwidth o wlth] dda. legths
Gat woctBar Height = hely kd - So"
Fe Lint values dtad $
TF (valued manchester) §
mataeda + Values, 4 4
Se Gah 205 feat tagths TH) Pp
int berth = act) Calta C1) |) Celnsble) mvetedecly)*
fwd KX
=3
=>
=>
=>
=>
>
=
=
D paswond Guorsl using Gave.
Grnport Sava. Security. SecwrtRamclow +
ee Gor. UH]. Bated ys,
fom Jove. Capt. Ciphees
‘enporst Sara. colph. keg Gemerstor *
Swnpook Sova. evapo. Scoxetkey,
public clatr passwd enerstr §
public Ghote sh Qerrate patcword (judd heath) 3 ,
final shi cheroestat 2 MAE CREFG HIT KLM NopaRguy xyz 012 24rg
. diet PAGO ce EIB <0
FeLi too; Sedat, 544) f a ;
Petre pees hee pamela dog Ds
a password toed OY5
%
purlte Cte hesug emergrtpacsioree ( cheseg petsrore, , Secuedkey)
thaer Ex ception z
Cipher cipher =» ofpher. AGSncdomce( AES")
bytel? enogpedayies = Cipher, clofinal [prstond getaytercy)
nicl Bates, qcttncodert), oneedIoetoveg Conerap ed bytes):
Jerrad Revebheyl) rows
KeyGener A keyQnurcy ¢ heyGeneracoe, ALn clon Pettion .
hey Ginurater, init 12 ¢) - 0 cane) 5
?
publte she seceelley
} sclen hetPenecd re, grerdeben Dypebtic static Void maim Shia anycy) J.
4
Sing paicsduel = gonvradiepoetnoerd Us,
S09 [SGenected paccwnd? "4 prccoerd)-
Seevelhey ceovetheg ey Jerome Seereeteers( x
hey eneny Plaspanel - ener rtp torso! ( prrpvaneel !, cecrctber) ,
s.o.p Energplecl pechwards "2 ene pholporsward)s :
Shing Aecraptedpetentarel pe cece dedprtevonel (evonyp teen dk
sop ls Deeg ted poeswoord s” talecnpledpagwerd)>
4
etch, Lexteption ¢) J
c. printcteck Trace ()5 :
4
j
q