Test your Java skills – Series IV

Java Coding Skills

Java Coding Skills – Test your knowledge

介绍: This is another Java tips series. We have mainly focused on the coding and implementation part. We have discussed different common Java implementations with coding examples. You can test it directly by creating your own Java code. Hope this will help you understand the basic things in core Java.







How to convert an infix expression to postfix expression?

一: 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.

进口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();

theStack = new Stack(stackSize);

}

public String doTrans() {

为 (int j = 0; Ĵ < input.length(); J ) {

char ch = input.charAt(Ĵ);

switch (ch) {

case ‘ ’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(&#8216;:

theStack.push(ch);

break;

case ‘)’:

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

而 (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

public void gotOper(char opThis, int prec1) {

而 (!theStack.isEmpty()) {

char opTop = theStack.pop();

如果 (opTop == ‘(&#8216;) {

theStack.push(opTop);

break;

}

其他 {

int prec2;

如果 (opTop == ‘ ’ || opTop == ‘-‘)

prec2 = 1;

其他

prec2 = 2;

如果 (prec2 < prec1)

{

theStack.push(opTop);

break;

} 其他

output = output + opTop;

}

}

theStack.push(opThis);

}

public void gotParen(char ch){

而 (!theStack.isEmpty()) {

char chx = theStack.pop();

如果 (chx == ‘(&#8216;)

break;

其他

output = output + chx;

}

}

公共静态无效的主要(串[] 参数) 抛出IOException异常 {

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

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + output + ‘n’);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

The above code sample will produce the following result.

124*5/+7-36/+

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

How to implement Queue?

一: 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.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(项目);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

而 (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

公共静态无效的主要(串[] 参数) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

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

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

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

empList.addItems(hList);

System.out.println(“The employees’ names are:”);

而 (empList.hasItems()) {

Employee emp = empList.dequeue();

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

}

}

}

class Employee {

` public String lastName;

public String firstName;

public Employee() {

}

public Employee(String last, String first) {

this.lastName = last;

this.firstName = first;

}

public String toString() {

return firstName + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

非常(last, first);

}

}

The above code sample will produce the following result.

The employees’ names are:

T D

G B

F S

How to reverse a string using stack?

一: 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

进口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);

为 (INT I = 0; 我 < input.length(); 我 ) {

char ch = input.charAt(我);

theStack.push(ch);

}

output = “”;

而 (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

公共静态无效的主要(串[] 参数) 抛出IOException异常 {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

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

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

 

}

}

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ







How to check whether antialiasing is enabled or not?

一: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, 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) systems.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

进口javax.swing.JFrame;

公共类主 {

公共静态无效的主要(串[] 参数) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(真);

}

}

class MyComponent extends JComponent {

public void paint(Graphics 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);

}

}

The above code sample will produce the following result.

False

False

False

How to display colors in a frame?

一: 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;

进口javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

诠释[] data = new int[width * height];

int index = 0;

为 (INT I = 0; 我 < height; 我 ) {

int red = (我 * 255) / (height – 1);

为 (int j = 0; Ĵ < width; J ) {

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

int blue = 128;

data[index ] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

如果 (image == null)

initialize();

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

}

公共静态无效的主要(串[] 参数) {

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

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

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(真);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.








What is threading in java?

一: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, 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(), etc.) 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?

一: 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.

进口的软件包java.awt。*;

import java.awt.event.*

导入javax.swing中。

public class Main extends JPanel {

串[] 类型= { “Serif”,”SansSerif”};

诠释[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

串[] stylenames =

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

public void paint(Graphics g) {

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

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

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

g.setFont(font);

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

g.drawString(名称, 20, (f * 4 + s + 1) * 20);

}

}

}

公共静态无效的主要(串[] 一) {

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(真);

}

}

The above code sample will produce the following result.

Different font names are displayed in a frame.

How to draw a line using GUI?

一: 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.

进口的软件包java.awt。*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

进口javax.swing.JFrame;

public class Main extends JApplet {

public void init() {

的setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

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

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

}

公共静态无效的主要(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().加(“Center”, applet);

applet.init();

f.pack();

f.setSize(新尺寸(300, 300));

f.setVisible(真);

}

}

The above code sample will produce the following result.

Line is displayed in a frame.

How to display a message in a new frame?

一: 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.

进口的软件包java.awt。*;

import java.awt.font.FontRenderContext;

java.awt.geom.Rectangle2D金额;

进口javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics 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, “和”, 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 = (float) bounds.getWidth();

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

}

公共静态无效的主要(串[] 参数) {

JFrame f = new JFrame();

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

f.setSize(450, 350);

f.setVisible(真);

}

}

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.







How to display a pie chart using a frame?

一: 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 () 方法. And the completed chart is displayed on a JFrame.

进口了java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

进口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, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

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

}

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

double total = 0.0D;

为 (INT I = 0; 我 < slices.length; 我 ) {

total = slices[我].值;

}

double curValue = 0.0D;

int startAngle = 0;

为 (INT I = 0; 我 < slices.length; 我 ) {

startAngle = (诠释) (curValue * 360 / 总);

int arcAngle = (诠释) (slices[我].值 * 360 / 总);

g.setColor(slices[我].color);

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

startAngle, arcAngle);

curValue = slices[我].值;

}

}

}

公共类主 {

公共静态无效的主要(串[] argv) {

JFrame frame = new JFrame();

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

frame.setSize(300, 200);

frame.setVisible(真);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

 

============================================= ============================================== 在亚马逊上购买最佳技术书籍,en,电工CT Chestnutelectric,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share