重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
代码如下:
创新互联主营邛崃网站建设的网络公司,主营网站建设方案,重庆APP开发,邛崃h5成都微信小程序搭建,邛崃网站营销推广欢迎邛崃等地区企业咨询
import java.util.Arrays;
class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
}
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
// 创建一个包含5个元素的数组
Circle[] circles = { new Circle(2), new Circle(10), new Circle(8), new Circle(4), new Circle(12) };
System.out.println(Arrays.toString(circles));
// 排序
Arrays.sort(circles, (x, y) - Integer.compare(x.getRadius(), y.getRadius()));
System.out.println(Arrays.toString(circles));
// 查找半径为 9 的圆
int index = Arrays.binarySearch(circles, 9, (x, y) - ((Circle)x).getRadius() - (int)y);
System.out.println(index =0 ? circles[index] : "没有找到半径为 9 的圆。");
// 查找半径为 10 的圆
index = Arrays.binarySearch(circles, 10, (x, y) - ((Circle)x).getRadius() - (int)y);
System.out.println(index =0 ? circles[index] : "没有找到半径为 10 的圆。");
// 拷贝数组
Circle[] circles2 = Arrays.copyOf(circles, circles.length);
System.out.println(Arrays.toString(circles2));
}
}
花了我将近一个小时的时间摆弄,你还不舍得给分
第一个类
/**************************************************************************
* 该类为启动类,运行该类,将跳出输入数组对话框,输入的数字之间用逗号隔开,若输入
* 的不是数字有可能出现异常,请自己处理。输入的数字最大个数为100,也可以修改处理
* 更大个数的数组。
**************************************************************************/
package terry.test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.EventListener;
import java.util.StringTokenizer;
public class InputData extends JFrame implements ActionListener
{
Container con=this.getContentPane();
JButton button1=new JButton("确定");
JButton button2=new JButton("取消");
JLabel label=new JLabel("请输入数组:");
JTextField text=new JTextField("数字之间用逗号隔开");
Panel panel1=new Panel();
Panel panel2=new Panel();
@SuppressWarnings("deprecation")
public InputData()
{
super("输入有序数据对话框");
con.setLayout(new GridLayout(2,1));
panel1.add(label);
panel1.add(text);
con.add(panel1);
button1.addActionListener(this);
panel2.add(button1);
button2.addActionListener(this);
panel2.add(button2);
con.add(panel2);
this.setSize(300,200);
this.show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button1)
{
String dataString=text.getText();//截取写入的数组,现在还是一个字符串
ordArray arr=new ordArray(100);//生成排序类的实例;
//以下为处理整个字符串,转化为整型数组。
if(dataString!=null)
{
StringTokenizer s=new StringTokenizer(dataString,",");
while(s.hasMoreTokens())
{
int temp=0;
try
{
temp=(new Integer(s.nextToken())).intValue();
}catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "在数组中,请输入整数值!");
}
arr.insert(temp);
}
}
this.dispose();
new InputSearchApp(arr);
}
}
public static void main(String args[])
{
new InputData();
}
}
第二个类
/**************************************************
* InputData实例向该类的实例传递了orderArray参数变量*
* *
*/
package terry.test;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class InputSearchApp extends JFrame implements ActionListener{
Container con=this.getContentPane();
JButton button1=new JButton("确定");
JButton button2=new JButton("取消");
JLabel label=new JLabel("请输入要查找的数值:");
JTextField text=new JTextField(10);
ordArray arr=null;
Panel panel1=new Panel();
Panel panel2=new Panel();
public InputSearchApp(ordArray testArray)
{
super("输入有序数据对话框");
arr=testArray;
con.setLayout(new GridLayout(2,1));
panel1.add(label);
panel1.add(text);
con.add(panel1);
button1.addActionListener(this);
panel2.add(button1);
button2.addActionListener(this);
panel2.add(button2);
con.add(panel2);
this.setSize(200,200);
this.show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button1)
{
String dataString=text.getText();
int searchKey= (new Integer(dataString)).intValue();
boolean success=arr.find(searchKey);
if(success)
{
this.dispose();
JOptionPane.showMessageDialog(null, ("查找到数据"+searchKey));
}
else
{
JOptionPane.showMessageDialog(null, ("没有查找到数据"+searchKey));
}
}
}
}
第三个类2分查找类
package terry.test;
public class ordArray {
private int[]a;
private int nElems;
public ordArray(int max)
{
a=new int[max];
nElems=0;
}
public int size()
{
return nElems;
}
public boolean find(int searchKey)
{
return recFind(searchKey,0,nElems-1);
}
private boolean recFind(int searchKey,int lowerBound,int upperBound)
{
int curIn,theindex;
//boolean flag=false;
curIn=(lowerBound+upperBound)/2;
if(a[curIn]==searchKey)
theindex=curIn;
else if(lowerBoundupperBound)
theindex=nElems;
else
{
if(a[curIn]searchKey)
return recFind(searchKey,lowerBound,curIn-1);
else
return recFind(searchKey,curIn+1,upperBound);
}
if(theindex!=this.size())
return true;
else
return false;
}
public void insert(int value)
{
int j;
for(j=0;jnElems;j++)
if(a[j]value)
break;
for(int k=nElems;kj;k--)
a[k]=a[k-1];
a[j]=value;
nElems++;
}
}
做什么事都要学会GOOGLE。
搜索JAVA记事本。
你新建一个类叫TEST。
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JFrame;
public class Test extends JFrame implements ActionListener {
/**
* Method main
*
*
* @param args
*
*/
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File"), edit = new Menu("Edit"), help = new Menu(
"Help");
MenuItem[] menuItem = { new MenuItem("New"), new MenuItem("Open"),
new MenuItem("Save"), new MenuItem("Exit"),
new MenuItem("Select All"), new MenuItem("Copy"),
new MenuItem("Cut"), new MenuItem("Paste"), new MenuItem("Help") };
TextArea textArea = new TextArea();
String fileName = "NoName";
Toolkit toolKit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolKit.getSystemClipboard();
// opne and close message dialogs
private FileDialog openFileDialog = new FileDialog(this, "Open File",
FileDialog.LOAD);
private FileDialog saveFileDialog = new FileDialog(this, "Save File",
FileDialog.SAVE);
public static void main(String[] args) {
// TODO: Add your code here
Test MyEdit = new Test();
MyEdit.show();
}
/**
* Method MiniEdit
*
*
*/
public Test() {
// TODO: Add your code here
setTitle("MiniEdit");
setFont(new Font("Times New Roman", Font.PLAIN, 15));
setBackground(Color.white);
setSize(500, 500);
setMenuBar(menuBar);
menuBar.add(file);
menuBar.add(edit);
menuBar.add(help);
for (int i = 0; i 4; i++) {
file.add(menuItem[i]);
edit.add(menuItem[i + 4]);
}
help.add(menuItem[8]);
add(textArea);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
System.exit(0);
}
});
// add actionListener
for (int i = 0; i menuItem.length; i++) {
menuItem[i].addActionListener(this);
}
}
/**
* Method actionPerformed
*
*
* @param e
*
*/
public void actionPerformed(ActionEvent e) {
// TODO: Add your code here
Object eventSource = e.getSource();
if (eventSource == menuItem[0])// newItem
{
textArea.setText("");
}
else if (eventSource == menuItem[1])// OpenItem
{
openFileDialog.show();
fileName = openFileDialog.getDirectory() + openFileDialog.getFile();
if (fileName != null) {
openFile(fileName);
}
}
else if (eventSource == menuItem[2])// SaveItem
{
saveFileDialog.show();
fileName = saveFileDialog.getDirectory() + saveFileDialog.getFile();
if (fileName != null) {
writeFile(fileName);
}
}
else if (eventSource == menuItem[3])// exitItem
{
System.exit(0);
}
else if (eventSource == menuItem[4])// Select All
{
textArea.selectAll();
} else if (eventSource == menuItem[5])// copy
{
String text = textArea.getSelectedText();
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, null);
}
else if (eventSource == menuItem[6])// cut
{
String text = textArea.getSelectedText();
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, null);
textArea.replaceText("", textArea.getSelectionStart(), textArea
.getSelectionEnd());
}
else if (eventSource == menuItem[7])// Paste
{
Transferable contents = clipboard.getContents(this);
if (contents == null)
return;
String text;
text = "";
try {
text = (String) contents
.getTransferData(DataFlavor.stringFlavor);
} catch (Exception ex) {
}
textArea.replaceText(text, textArea.getSelectionStart(), textArea
.getSelectionEnd());
} else if (eventSource == menuItem[8]) {
// JOptionPane.showMessageDialog(null,"This is a MiniEdit.");
}
}
// Read file
public void openFile(String fileName) {
try {
File file = new File(fileName);
FileReader readIn = new FileReader(file);
int size = (int) file.length();
int charsRead = 0;
char[] content = new char[size];
while (readIn.ready())
charsRead += readIn.read(content, charsRead, size - charsRead);
readIn.close();
textArea.setText(new String(content, 0, charsRead));
} catch (Exception e) {
System.out.println("Error opening file!");
}
}
// write file
public void writeFile(String fileName) {
try {
File file = new File(fileName);
FileWriter write = new FileWriter(file);
write.write(textArea.getText());
write.close();
} catch (Exception e) {
System.out.println("Error closing file!");
}
}
}
Jython(原JPython),是一个用Java语言写的Python解释器。
在没有第三方模块的情况下,通常选择利用Jython来调用Python代码,
它是一个开源的JAR包,你可以到官网下载
一个HelloPython程序
import org.python.util.PythonInterpreter;
public class HelloPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('hello')");
}
}
什么是PythonInterpreter?它的中文意思即是“Python解释器”。我们知道Python程序都是通过解释器来执行的,我们在Java中创建一个“解释器”对象,模拟Python解释器的行为,通过exec("Python语句")直接在JVM中执行Python代码,上面代码的输出结果为:hello
在Jvm中执行Python脚本
interpreter.execfile("D:/labs/mytest/hello.py");
如上,将exec改为execfile就可以了。需要注意的是,这个.py文件不能含有第三方模块,因为这个“Python脚本”最终还是在JVM环境下执行的,如果有第三方模块将会报错:java ImportError: No module named xxx
仅在Java中调用Python编写的函数
先完成一个hello.py代码:
def hello():
return 'Hello'
在Java代码中调用这个函数:
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class HelloPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:/labs/hello.py");
PyFunction pyFunction = interpreter.get("hello", PyFunction.class); // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyObject pyObject = pyFunction.__call__(); // 调用函数
System.out.println(pyObject);
}
}
上面的代码执行结果为:Hello
即便只是调用一个函数,也必须先加载这个.py文件,之后再通过Jython包中所定义的类获取、调用这个函数。
如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”,例如:
__call__(new PyInteger(a), new PyInteger(b))
a,b的类型为Java中的int型,还有诸如:PyString(String string)、PyList(IteratorPyObject iter) 等。
详细可以参考官方的api文档。
包含第三方模块的情况:一个手写识别程序
这是我和舍友合作写的一个小程序,完整代码在这里:
,界面上引用了core java上的一段代码。Python代码是舍友写的,因为在Python程序中使用了第三方的NumPy模块,导致无法通过Jython执行。下面这个方法纯粹是个人思路,没有深入查资料。 核心代码如下:
import java.io.*;
class PyCaller {
private static final String DATA_SWAP = "temp.txt";
private static final String PY_URL = System.getProperty("user.dir") + "\\test.py";
public static void writeImagePath(String path) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter(new File(DATA_SWAP)));
} catch (IOException e) {
e.printStackTrace();
}
pw.print(path);
pw.close();
}
public static String readAnswer() {
BufferedReader br;
String answer = null;
try {
br = new BufferedReader(new FileReader(new File(DATA_SWAP)));
answer = br.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
public static void execPy() {
Process proc = null;
try {
proc = Runtime.getRuntime().exec("python " + PY_URL);
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 测试码
public static void main(String[] args) throws IOException, InterruptedException {
writeImagePath("D:\\labs\\mytest\\test.jpg");
execPy();
System.out.println(readAnswer());
}
}
实际上就是通过Java执行一个命令行指令。