Ntsuam xyuas koj Java kawm – Series IV

Java Coding Skills

Java Coding SkillsTest your knowledge

Taw qhia: Qhov no yog lwm Java tswv yim series. Peb muaj mas teem rau qhov coding thiab siv qhov. Peb tau tham txog ntau hom kev siv Java nrog coding piv txwv. Koj yuav tau kuaj nws ncaj qha los ntawm kev tsim koj tus kheej Java code. Hope this will help you understand the basic things in core Java.







How to convert an infix expression to postfix expression?

IB: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.

ntshuam java.io.IOException;

public class InToPost {

private Stack theStack;

private String input;

private String output = “”;

public InToPost(String in) {

input = in;

int stackSize = input.length();

Lub plawv = Tshoj tshiab(stackSize);

}

public String doTrans() {

rau (rau cov menyuam j = 0; j < input.length(); j ) {

char ch = input.charAt(j);

hloov (xubnt) {

case ‘+’:

case ‘-‘:

gotOper(xubnt, 1);

so;

case ‘*’:

case ‘/’:

gotOper(xubnt, 2);

so;

case ‘(‘:

Xovtooj khwb rho tawm(xubnt);

so;

case ‘)’:

gotParen(xubnt);

so;

vim:

output = output + xubnt;

so;

}

}

Thaum (!Lub khwb rhuav tag()) {

output = output + theStack.pop();

}

System.out.println(tso zis);

return output;

}

public void gotOper(char opThis, int prec1) {

Thaum (!Lub khwb rhuav tag()) {

char opTop = theStack.pop();

Yog hais tias (opTop == ‘(‘) {

Xovtooj khwb rho tawm(opTop);

so;

}

ntxiv {

int prec2;

Yog hais tias (opTop == ‘+’ || opTop == ‘-‘)

prec2 = 1;

ntxiv

prec2 = 2;

Yog hais tias (prec2 < prec1)

{

Xovtooj khwb rho tawm(opTop);

so;

} ntxiv

output = output + opTop;

}

}

Xovtooj khwb rho tawm(opThis);

}

public void gotParen(nplua){

Thaum (!Lub khwb rhuav tag()) {

char chx = theStack.pop();

Yog hais tias (chx == ‘(‘)

so;

ntxiv

output = output + chx;

}

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws IOException {

String input = “1+2*4/5-7+3/6”;

String output;

InToPost theTrans = new InToPost(tswv yim);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + tso zis + 'n');

}

Hoob Kawm {

qhov hauv maxSize;

private char[] stackArray;

ntiav;

Pej xeem Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

nyob saum toj kawg nka -1;

}

pej xeem tsis txhob raug thawb(char j) {

stackArray[++saum toj kawg n] = j;

}

public char pop() {

return stackArray[saum toj kawg n–];

}

public char peek() {

return stackArray[saum toj kawg n];

}

Pej xeem boolean ntxias() {

rov qab mus (sab saum toj = -1);

}

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

124*5/+7-36/+

Postfix is 124*5/+7-36/+

How to implement Queue?

IB: Following example shows how to implement a queue in an employee structure. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

chaw nres nkoj java..util.Linkedlist;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(yam khoom);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

rov qab mus !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

Thaum (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue(new HourlyEmployee(“T”, “D”));

hList.enqueue(new HourlyEmployee(“G”, “B”));

hList.enqueue(new HourlyEmployee(“F”, “S”));

empList.addItems(hList);

System.out.println(“The employeesnames are:”);

Thaum (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + ” ” + emp.lastName);

}

}

}

kawm ua hauj lwm {

` public String lastName;

public String firstName;

neeg ua hauj lwm rau pej xeem() {

}

neeg ua hauj lwm rau pej xeem(String last, String first) {

this.lastName = last;

this.firstName = first;

}

Pej xeem stringing torsting() {

rov qab los ua ntej + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

super(last, thawj);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

The employeesnames are:

T D

G B

F S

How to reverse a string using stack?

IB: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class

ntshuam java.io.IOException;

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

rau (rau cov menyuam kuv = 0; Kuv < input.length(); i ) {

char ch = input.charAt(Kuv);

Xovtooj khwb rho tawm(xubnt);

}

output = “”;

Thaum (!Lub khwb rhuav tag()) {

char ch = theStack.pop();

output = output + xubnt;

}

return output;

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws IOException {

String input =Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(tswv yim);

output = theReverser.doRev();

System.out.println(“Reversed: ” + tso zis);

}

Hoob Kawm {

qhov hauv maxSize;

private char[] stackArray;

ntiav;

Pej xeem Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

nyob saum toj kawg nka -1;

}

pej xeem tsis txhob raug thawb(char j) {

stackArray[++saum toj kawg n] = j;

}

public char pop() {

return stackArray[saum toj kawg n–];

}

public char peek() {

return stackArray[saum toj kawg n];

}

Pej xeem boolean ntxias() {

rov qab mus (sab saum toj = -1);

}

 

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ







How to check whether antialiasing is enabled or not?

IB: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (qhov no, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) tshuab.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

import javax.swing.JFrame;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(tseeb);

}

}

class MyComponent extends JComponent {

pej xeem tsis txhob mob(Nraaj g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

False

False

False

How to display colors in a frame?

IB: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

pej xeem tsis muaj dabtsis initialize() {

int width = getSize().width;

int height = getSize().qhov siab;

rau cov menyuam[] cov ntaub ntawv = tshiab[width * qhov siab];

int index = 0;

rau (rau cov menyuam kuv = 0; Kuv < qhov siab; i ) {

int red = (Kuv * 255) / (qhov siab – 1);

rau (rau cov menyuam j = 0; j < width; j ) {

int green = (j * 255) / (width – 1);

int blue = 128;

cov ntaub ntawv[index++] = (liab < < 16) | (ntsuab < < 8) | blue;

}

}

image = new BufferedImage

(width, qhov siab, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, qhov siab, cov ntaub ntawv, 0, width);

}

pej xeem tsis txhob mob(Nraaj g) {

Yog hais tias (image == null)

initialize();

g.drawImage(image, 0, 0, no);

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame f = new JFrame(“Display Colours”);

f.getContentPane().ntxiv(new Main());

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.Exit(0);

}

});

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Displays all the colours in a frame.








What is threading in java?

IB: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. Tamsim no, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), thiab lwm yam.) of your applet; we speak of this thread as the applet’s thread. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.

How to display text in different fonts?

IB: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.

import java.awt.*;

import java.awt.event.*

import javax.swing.*

public class Main extends JPanel {

Txoj hlua[] yam = { “Serif”,”SansSerif”};

rau cov menyuam[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

Txoj hlua[] stylenames =

{ “Plain”, “Italic”, “Bold”, “Bold & Italic” };

pej xeem tsis txhob mob(Nraaj g) {

rau (int f = 0; f < type.length; f++) {

rau (int s = 0; s < styles.length; s++) {

Font font = new Font(hom[f], styles[s], 18);

g.setFont(font);

String name = type[f] + ” ” + stylenames[s];

g.g.drawString(lub npe, 20, (f * 4 + s + 1) * 20);

}

}

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] ib) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.Exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Different font names are displayed in a frame.

How to draw a line using GUI?

IB: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

import javax.swing.JFrame;

public class Main extends JApplet {

pej xeem zam() {

setBackground(Color.white);

setForeground(Color.white);

}

pej xeem tsis txhob mob(Nraaj g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(txho tshauv.);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString(“Line”, x, 250);

}

pej xeem tsis muaj dabtsis loj zoo li qub(String s[]) {

JFrame f = new JFrame(“Line”);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.Exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().ntxiv(“Center”, applet);

applet.init();

f.pack();

f.setSize(new Dimension(300, 300));

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Line is displayed in a frame.

How to display a message in a new frame?

IB: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component. And then the message is displayed on a JPanel component.

import java.awt.*;

import java.awt.font.FontRenderContext;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

pej xeem tsis txhob mob(Nraaj g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font(“Serif”, Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);

paintHorizontallyCenteredText(g2, “thiab”, 200, 125);

paintHorizontallyCenteredText(g2, “Support”, 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

float width = (ntab) bounds.getWidth();

g2.drawString(s, centerX – width / 2, baselineY);

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame f = new JFrame();

f.getContentPane().ntxiv(new Main());

f.setSize(450, 350);

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

JAVA and J2EE displayed in a new Frame.







How to display a pie chart using a frame?

IB: Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () txujci. And the completed chart is displayed on a JFrame.

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

import javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, daj lug...), new Slice(15, liab xim liab..) };

MyComponent() {}

pej xeem tsis txhob mob(Nraaj g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

rau (rau cov menyuam kuv = 0; Kuv < slices.length; i ) {

total += slices[Kuv].tus nqi;

}

double curValue = 0.0D;

int startAngle = 0;

rau (rau cov menyuam kuv = 0; Kuv < slices.length; i ) {

startAngle = (rau cov menyuam) (curValue * 360 / tag nrho);

int arcAngle = (rau cov menyuam) (slices[Kuv].tus nqi * 360 / tag nrho);

g.g.setcolor(slices[Kuv].xim);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue += slices[Kuv].tus nqi;

}

}

}

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] av) {

JFrame frame = new JFrame();

frame.getContentPane().ntxiv(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Displays a piechart on a frame.

 

============================================= ============================================== Yuav zoo TechAlpine phau ntawv rau Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Txaus siab rau qhov blog? Tshaj tawm lus thov :)

Follow by Email
LinkedIn
LinkedIn
Share