java算法写计算机代码 java编写一个简单的计算器,能够实现

求:用JAVA语言编写的银行家算法的源代码import java.util.*;
class ThreadTest {
static int type = 4, num = 10; //定义资源数目和线程数目
static int[] resource = new int[type]; //系统资源总数
//static int[] copyResource = new int[type]; //副本
static Random rand = new Random();
static Bank[] bank = new Bank[num]; //线程组
Bank temp = new Bank();
public void init() {
//初始化组中每个线程,随机填充系统资源总数
for(int i = 0; itype; i)
resource[i] = rand.nextInt(10)80;
System.out.print("Resource:");
for(int i = 0; itype; i)
System.out.print(" "resource[i]);
System.out.println("");
for(int i = 0; ibank.length; i)
bank[i] = new Bank("#"i);
}
public ThreadTest4() {
init();
}
class Bank extends Thread {
//银行家算法避免死锁
public int[]
max = new int[type], //总共需求量
need = new int[type], //尚需资源量
allocation = new int[type]; //已分配量
private int[]
request = new int[type], //申请资源量
copyResource = new int[type]; //资源副本
private boolean isFinish = false; //线程是否完成
int[][] table = new int[bank.length][type*4]; //二维资源分配表
private void init() {
// 随机填充总共、尚需、已分配量
synchronized(resource) {
for(int i = 0; itype; i) {
max[i] = rand.nextInt(5)10;
need[i] = rand.nextInt(10);
allocation[i] = max[i] - need[i];
resource[i] -= allocation[i]; //从系统资源中减去已分配的
}
printer();
for(int i = 0; itype; i) {
if(resource[i]0) {
//若出现已分配量超出系统资源总数的错误则退出
System.out.println("The summation of Threads' allocations is out of range!");
System.exit(1);
}
}
}
}
public Bank(String s) {
setName(s);
init();
start();
}
public Bank() {
//none
}
public void run() {
try {
sleep(rand.nextInt(2000));
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
while(true) {
//程序没有完成时一直不断申请资源
if(askFor() == false) {
try {
sleep(1000);
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
else
tryRequest();
if(noNeed() == true)
break;
}
//休眠一段时间模拟程序运行
try {
sleep(1000);
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(getName()" finish!");
synchronized(resource) {
//运行结束释放占有资源
for(int i = 0; itype; i) {
resource[i]= allocation[i];
need[i] = allocation[i] = max[i] = 0;
}
}
}
private void printer() {
//打印当前资源信息
System.out.print(getName()" Max:");
for(int i = 0; itype; i)
System.out.print(" "max[i]);
System.out.print(" Allocation:");
for(int i = 0; itype; i)
System.out.print(" "allocation[i]);
System.out.print(" Need:");
for(int i = 0; itype; i)
System.out.print(" "need[i]);
System.out.print(" Available:");
for(int i = 0; itype; i)
System.out.print(" "resource[i]);
System.out.println("");
}
private boolean askFor() {
//随机产生申请资源量并检测是否超标
boolean canAsk = false;
for(int i = 0; itype; i) {
request[i] = rand.nextInt(20);
//防止申请量超过所需量
if(request[i]need[i])
request[i] = need[i];
}
for(int i = 0; itype; i) //防止随机申请资源全为0
if(request[i]0)
canAsk = true;
synchronized(resource) {
//锁住可供资源检查是否超标
for(int i = 0; itype; i) {
if(request[i]resource[i])
//如果申请资源超过可供资源则等待一段时间后重新申请
return false;
}
}
return canAsk;
}
private void tryRequest() {
//创建副本尝试分配请求
synchronized(resource) {
for(int i = 0; itype; i)
//依然要防止请求量超出范围
if(request[i]resource[i])
return;
for(int i = 0; itype; i) {
//复制资源量并减去需求量到一个副本上
copyResource[i] = resource[i];
copyResource[i] -= request[i];
}
System.out.print(getName()" ask for:");
for(int i = 0; itype; i)
System.out.print(" "request[i]);
System.out.println("");
if(checkSafe() == true) {
//如果检查安全则将副本值赋给资源量并修改占有量和需求量
for(int i = 0; itype; i) {
resource[i] = copyResource[i];
allocation[i]= request[i];
need[i] -= request[i];
}
System.out.println(getName()" request succeed!");
}
else
System.out.println(getName()" request fail!");
}
}
private boolean checkSafe() {
//银行家算法检查安全性
synchronized(bank) {
//将线程资源信息放入二维资源分配表检查安全性,0~type可用资源/type~type*2所需资源/type*2~type*3占有资源/type*3~-1可用 占用资源
for(int i = 0; ibank.length; i) {
for(int j = type; jtype*2; j) {
table[i][j] = bank[i].need[j%type];
}
for(int j = type*2; jtype*3; j) {
table[i][j] = bank[i].allocation[j%type];
}
}
//冒泡排序按需求资源从小到大排
for(int i = 0; ibank.length; i) {
for(int j = i; jbank.length-1; j) {
sort(j, 4);
}
}
//进行此时刻的安全性检查
for(int i = 0; itype; i) {
table[0][i] = copyResource[i];
table[0][i type*3] = table[0][i]table[0][i type*2];
if(table[0][i type*3]table[1][i type])
return false;
}
for(int j = 1; jbank.length-1; j) {
for(int k = 0; ktype; k) {
table[j][k] = table[j-1][k type*3];
table[j][k type*3] = table[j][k]table[j][k type*2];
if(table[j][k type*3]table[j 1][k type])
return false;
}
}
}
return true;
}
private void sort(int j, int k) {
//递归冒泡排序
int tempNum;
if(table[j][k]table[j 1][k]) {
for(int i = type; itype*2; i) {
tempNum = table[j][i];
table[j][i] = table[j 1][i];
table[j 1][i] = tempNum;
}
/*temp = bank[j];
bank[j] = bank[j 1];
bank[j 1] = temp;*/
}
else if(table[j][k] == table[j 1][k]ktype*2) //此资源量相同时递归下一个资源量排序并且防止超出范围
sort(j, k 1);
}
private boolean noNeed() {
//是否还需要资源
boolean finish = true;
for(int i = 0; itype; i) {
if(need[i] != 0) {
finish = false;
break;
}
}
return finish;
}
}
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
//后台线程,设定程序运行多长时间后自动结束
new Timeout(30000, "---Stop!!!---");
}
}
用JAVA设计 , 实现并测试一个计算机类,它包括如下内容//computer.java
package com.ecit;
public class Computer {
private String pcName; //计算机品牌
private String pcColor; //计算机颜色
private String pcType; //CPU型号
private int pcPrice; //价格
private String pcState; //工作状态
public Computer(){
}
public Computer(String pcName,String pcColor,String pcType,int pcPrice,String pcState)
{
this.pcName=pcName;
this.pcColor=pcColor;
this.pcType=pcType;
this.pcPrice=pcPrice;
this.pcState=pcState;
}
public String toString() //输出的方法
{
return "pcName:" pcName "pcColor:" pcColor "pcType:"
pcType "pcPrice:" pcPrice "pcState:" pcState;
}
public String turnOnPc ( String pc_state,int pc_price ) //定义计算机打开的方法
{
return "pc_state:" pc_state "," "pc_price:" pc_price;
}
public String turnOffPc (String pc_state ) //定义计算机关闭的方法
{
return "pc_state:" pc_state;
}
public String hitchPc ( String pc_state )//定义计算机挂起的方法
{
return "pc_state:" pc_state;
}
public String getPcName() {
return pcName;
}
public void setPcName(String pcName) {
this.pcName = pcName;
}
public String getPcColor() {
return pcColor;
}
public void setPcColor(String pcColor) {
this.pcColor = pcColor;
}
public String getPcType() {
return pcType;
}
public void setPcType(String pcType) {
this.pcType = pcType;
}
public int getPcPrice() {
return pcPrice;
}
public void setPcPrice(int pcPrice) {
this.pcPrice = pcPrice;
}
public String getPcState() {
return pcState;
}
public void setPcState(String pcState) {
this.pcState = pcState;
}
}
//MyComputer.java
package com.ecit;
public class MyComputer {
public static void main(String[] args) {
Computer computer1=new Computer();
computer1.setPcName("长城");
computer1.setPcColor("白色");
computer1.setPcType("Intel");
computer1.setPcPrice(5200);
computer1.setPcState("空闲中");
System.out.println(computer1);
Computer computer2=new Computer("联想","黑色","AMD",5800,"工作中");
System.out.println(computer2.getPcName());
System.out.println(computer2);
}
}
如何用Java编写四则运算程序?(首先建个类,把这些复制粘贴进去)
import java.awt.*;
import javax.swing.*;
public class F {
JFrame frame = new JFrame("计算机");
JPanel pl = new JPanel();
JPanel p2 = new JPanel();
static JTextField show = new JTextField();
static JButton b0 = new JButton("0");
static JButton b1 = new JButton("1");
static JButton b2 = new JButton("2");
static JButton b3 = new JButton("3");
static JButton b4 = new JButton("4");
static JButton b5 = new JButton("5");
static JButton b6 = new JButton("6");
static JButton b7 = new JButton("7");
static JButton b8 = new JButton("8");
static JButton b9 = new JButton("9");
JButton bjia = new JButton(" ");
JButton bjian = new JButton("-");
JButton bcheng = new JButton("*");
JButton bchu = new JButton("/");
JButton bdian = new JButton(".");
JButton bdeng = new JButton("=");
JButton bqingchu = new JButton("清除");
public void y() {
pl.setLayout(new GridLayout(1, 1));
pl.add(show);
}
public void p() {
b1.addActionListener(new U());
b2.addActionListener(new U());
b3.addActionListener(new U());
b4.addActionListener(new U());
b5.addActionListener(new U());
b6.addActionListener(new U());
b7.addActionListener(new U());
b8.addActionListener(new U());
b9.addActionListener(new U());
b0.addActionListener(new U());
bjia.addActionListener(new Fu());
bjian.addActionListener(new Fu());
bcheng.addActionListener(new Fu());
bchu.addActionListener(new Fu());
bdeng.addActionListener(new Deng());
bqingchu.addActionListener(new Qing());
p2.setLayout(new GridLayout(6, 3));
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(b0);
p2.add(bjia);
p2.add(bjian);
p2.add(bcheng);
p2.add(bchu);
p2.add(bdian);
p2.add(bqingchu);
p2.add(bdeng);
}
public void o() {
frame.setLayout(new BorderLayout());
frame.add(pl, BorderLayout.NORTH);
frame.add(p2, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
F f = new F();
f.y();
f.p();
f.o();
}
}
(再新建个类 把这些也复制粘贴进去)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class U implements ActionListener {
public static String str = "";
public static String a = "";
public static String b = "";
public static String k = "";
public void actionPerformed(ActionEvent e) {
String w = e.getActionCommand();//字
if (k.equals("")) {
a= w;
F.show.setText(a);
} else {
b= w;
F.show.setText(b);
}
}
}
(再新建一个,把下面的复制粘贴)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Deng implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(U.a);
int b = Integer.parseInt(U.b);
int c = 0;
if (U.k.equals(" ")) {
c = ab;
} else
if (U.k.equals("-")) {
c = a - b;
} else
if (U.k.equals("*")) {
c = a * b;
} else
if (U.k.equals("/")) {
c = a / b;
} else {
}
String d = String.valueOf(c);
F.show.setText(d);
U.a = d;
U.b = "";
U.k = "";
}
}
(在建一个 复制粘贴)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Fu implements ActionListener {
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();//字
U.k = a;
}
}
(在建一个)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Qing implements ActionListener {
public void actionPerformed(ActionEvent e) {
U.a = "";
U.b = "";
U.k = "";
F.show.setText("");
}
}
JAVA 编写计算器要代码最简单的学javajava算法写计算机代码的时候自己编的java算法写计算机代码,很简单,能够连续输入计算式后进行计算
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**简易计算器 , 能够进行简单的计算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
//private JButton backButton;
String result="";//保存结果
StringBuilder sb = new StringBuilder();//保存要进行的计算式
int x = 0;//用来判断上一次的事件类型
String str = "123 456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算
public CalculatorA(){
frame = new JFrame("我的计算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i){
allButtons[i]= new JButton(str.substring(i,i 1));
}
clearButton = new JButton("CLEAR");
//backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//设置输入字体
public void setFondAndColor(){
field.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//设置字体从右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
//backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = resultstr;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
【java算法写计算机代码 java编写一个简单的计算器,能够实现】result = resultstr;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if(" *-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = resultstr;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result str);
arrayList.add(result);
arrayList.add(str);
result = result str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result str);
arrayList.add(result);
arrayList.add(str);
result = result str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-"," "};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j 1)));
//本地的数据格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j 1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j 1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i;
}
else {
for(int j=0;jlist.size();j){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1)) Double.parseDouble(list.get(j 1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i;
}
}
}
return list;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k){
if((c[k]= '0'c[k]= '9')|| c[k] == '.'){
s_temp= c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
用JAVA编写一个计算机/**
* 四则运算表达式计算
* @author penli
*
*/
public class Arithmetic {
public static void main(String args[]){
System.out.println(arithmetic("2.2 ((3 4)*2-22)/2*3.2"));
}
public static double arithmetic(String exp){
String result = parseExp(exp).replaceAll("[\\[\\]]", "");
return Double.parseDouble(result);
}
/**
* 解析计算四则运算表达式,例:2 ((3 4)*2-22)/2*3
* @param expression
* @return
*/
public static String parseExp(String expression){
//String numberReg="^((?!0)\\d (\\.\\d (?!0))?)|(0\\.\\d (?!0))$";
expression=expression.replaceAll("\\s ", "").replaceAll("^\\((. )\\)$", "$1");
String checkExp="\\d";
String minExp="^((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\]))[\\ \\-\\*\\/]((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\]))$";
//最小表达式计算
if(expression.matches(minExp)){
String result=calculate(expression);
return Double.parseDouble(result)=0?result:"[" result "]";
}
//计算不带括号的四则运算
String noParentheses="^[^\\(\\)] $";
String priorOperatorExp="(((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\]))[\\*\\/]((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\])))";
String operatorExp="(((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\]))[\\ \\-]((\\d (\\.\\d )?)|(\\[\\-\\d (\\.\\d )?\\])))";
if(expression.matches(noParentheses)){
Pattern patt=Pattern.compile(priorOperatorExp);
Matcher mat=patt.matcher(expression);
if(mat.find()){
String tempMinExp=mat.group();
expression=expression.replaceFirst(priorOperatorExp, parseExp(tempMinExp));
}else{
patt=Pattern.compile(operatorExp);
mat=patt.matcher(expression);
if(mat.find()){
String tempMinExp=mat.group();
expression=expression.replaceFirst(operatorExp, parseExp(tempMinExp));
}
}
return parseExp(expression);
}
//计算带括号的四则运算
String minParentheses="\\([^\\(\\)] \\)";
Pattern patt=Pattern.compile(minParentheses);
Matcher mat=patt.matcher(expression);
if(mat.find()){
String tempMinExp=mat.group();
expression=expression.replaceFirst(minParentheses, parseExp(tempMinExp));
}
return parseExp(expression);
}
/**
* 计算最小单位四则运算表达式(两个数字)
* @param exp
* @return
*/
public static String calculate(String exp){
exp=exp.replaceAll("[\\[\\]]", "");
String number[]=exp.replaceFirst("(\\d)[\\ \\-\\*\\/]", "$1,").split(",");
BigDecimal number1=new BigDecimal(number[0]);
BigDecimal number2=new BigDecimal(number[1]);
BigDecimal result=null;
String operator=exp.replaceFirst("^.*\\d([\\ \\-\\*\\/]). $", "$1");
if(" ".equals(operator)){
result=number1.add(number2);
}else if("-".equals(operator)){
result=number1.subtract(number2);
}else if("*".equals(operator)){
result=number1.multiply(number2);
}else if("/".equals(operator)){
result=number1.divide(number2);
}
return result!=null?result.toString():null;
}
}
看看对你有没有帮助 。不懂得继续探讨
寻求大神帮忙写Java代码,要用Dijkstra’s algorithm(迪杰斯特拉算法)package minRoad.no;
import java.util.Arrays;
//这个程序用来求得一个图的最短路径矩阵
public class ShortestDistance_V4 {
private static final int inf = Integer.MAX_VALUE;// 表示两个点之间无法直接连通
public static int[][] dijkstra(int[][] graph) {
int min, v, u = 0, n = graph.length;
int[] path = new int[n];
int[] dist = new int[n];
boolean[] s = new boolean[n];
Arrays.fill(s, false);
Arrays.fill(dist, inf);
for (int i = 0; in; i) {
dist[i] = graph[u][i];
if (i != udist[i]inf)
path[i] = u;
else
path[i] = -1;
}
s[u] = true;
while (true) {
min = inf;
v = -1;
// 找到最小的dist
for (int i = 0; in; i) {
if (!s[i]) {
if (dist[i]min) {
min = dist[i];
v = i;
}
}
}
if (v == -1) break;// 找不到更短的路径了
// 更新最短路径
s[v] = true;
for (int i = 0; in; i) {
if (!s[i]graph[v][i] != infdist[v]graph[v][i]dist[i]) {
dist[i] = dist[v]graph[v][i];
path[i] = v;
}
}
}
// 输出路径
int[] shortest = new int[n];
for (int i = 1; in; i) {
Arrays.fill(shortest, 0);
int k = 0;
shortest[k] = i;
while (path[shortest[k]] != 0) {
k;
shortest[k] = path[shortest[k - 1]];
}
k;
shortest[k] = 0;
}
int[] tmp = new int[shortest.length];
for (int i = 0; itmp.length; i) {
tmp[i] = shortest[tmp.length - i - 1];
}
return new int[][] { dist, tmp };
}
/**
* pre
*v0
*1,v1
*4,2,v2
* inf,7,-1,v3
* inf,5,1,3,v4
* inf, inf,inf,2,6,v5
* /pre
*
* *
*
* pre
* A--------30-------D
* |\∧|
* | \/ |
* |\/|
* |1010|
* |\/20
* |\/|
* |\/|
* |∨/∨
* 20BE
* |/∧
* |//
* |//
* |5/
* |/30
* |//
* |//
* ∨∠/
* C
* /pre
*
* @param args
*/
public static void main(String[] args) {
int[][] W1 = {
{0,10,20,30,inf },
{10,0,5,10,inf },
{20,5,0,inf,30 },
{ 30,10,inf,0,20 },
{ inf,inf,30,20,0 },
};
//
//
//int[][] W = {
//{0,1,4,inf,inf,inf },
//{1,0,2,7,5,inf },
//{4,2,0,inf,1,inf },
//{ inf,7,inf,0,3,2 },
//{ inf,5,1,3,0,6 },
//{ inf, inf,inf,2,6,0 }};
int[][] distAndShort = dijkstra(W1);
System.out.println(Arrays.toString(distAndShort[0]));
System.out.println(Arrays.toString(distAndShort[1]));
// distance: { 0, 1, 3, 7, 4, 9};
}
}
java算法写计算机代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java编写一个简单的计算器,能够实现、java算法写计算机代码的信息别忘了在本站进行查找喔 。

    推荐阅读