當前位置:首頁 » 編程語言 » java編程練習題

java編程練習題

發布時間: 2022-10-05 07:28:00

『壹』 簡單java編程題,運行成功追加20

1)用equals()方法判斷,Test
t=new
Test(2,4);
Test
t1=new
Test(2,4);是否相等。不相等
public
class
Test
{
private
int
a;
private
int
b;
public
Test(int
a,
int
b){
this.a
=
a;
this.b
=
b;
}
public
static
void
main(String[]
args)
{
Test
t=new
Test(2,4);
Test
t1=new
Test(2,4);
boolean
isEqual
=
t.equals(t1);
System.out.println(isEqual);
}
}
2)設計一種手段,讓t.equals(t1)相等.,結果相等。
public
class
Test
{
private
int
a;
private
int
b;
public
Test(int
a,
int
b){
this.a
=
a;
this.b
=
b;
}
public
static
void
main(String[]
args)
{
Test
t=new
Test(2,4);
Test
t1=new
Test(2,4);
boolean
isEqual
=
t.equals(t1);
System.out.println(isEqual);
}
public
boolean
equals(Object
o)
{
if(o
instanceof
Test){
Test
t2
=
(Test)
o;
return
t2.a
==
this.a
&&
t2.b
==
this.b;
}
return
false;
}
}
總結:如果子類不重寫Object.equals()方法,那麼兩個對象比較的是內存地址;如果子類重寫equals()方法,裡面可以根據自己的需要來定義,從而避免比較內存地址。。

『貳』 一道簡單的java編程題

import java.text.ParseException;

import java.text.SimpleDateFormat;
//日期類
public class Date {
private String year;
private String month;
private String day;

public Date(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
}
public void format(){
System.out.println(day + "/" + month + "/" + year);
}

public void calculate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
java.util.Date startDate = sdf.parse(year + "/" + "01" + "/" + "01");
java.util.Date inputDate = sdf.parse(year + "/" + month + "/" + day);
long resultDay = (inputDate.getTime() - startDate.getTime())/(24 * 1000 * 60 * 60);
System.out.println("第" + (resultDay + 1) + "天");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//測試類
public class Test {
public static void main(String[] args) {
Date date1 = new Date("2020","04","11");
Date date2 = new Date("2020","01","02");
date1.format();
date1.calculate();
date2.format();
date2.calculate();
}
}

『叄』 java編程十道題

1.
public class TestRandomArray
{
public static void main(String[] args)
{
int maxline = (int) (Math.random()*100);
int[] array = new int[maxline];
for(int i=0;i<maxline;i++)
{
int temp = (int) (Math.random()*100);
if(temp>=10&&temp<=99)
{
array[i] = temp;
}
else
i--;
}
for(int j=0;j<maxline;j++)
{
int max = array[0];

if(array[j]>max)
{
max=array[j];
array[j] = array[0];
array[0] = max;

}
}
for(int k=0;k<maxline;k++)
{
System.out.print(array[k]+" ");
}
}
}

2.
public class TestNumber100
{
public static void main(String[] args)
{
for(int i=1;i<100;i++)
{
if(i%3==0&&(i%5!=0)&&(i%9!=0))
System.out.println(i+" ");
else
continue;
}
}
}

3.貌似沒結果
public class Test3
{
public static void main(String[] args)
{
/*for(int i=0;i<=9;i++)
{
for(int j=0;j<=9;j++)
{
int code = 10000+i*1000+j*100+23;
if((code%57)==0&&(code%67)==0&&i!=j)
{
System.out.println("x="+i+","+"y="+j);
}
else
System.out.println(i+" "+j);
}
}*/

for(int i=10023;i<=19923;i++)
if(i==0&&i==0)
System.out.println(i+" ");
}
}

4.
class Caculate {
int money;
Caculate(){
money = 10;
}
public int charge (int distance){
if (distance < 3){
money = 10;
}
if ((distance >= 3) && distance < 15)
{
money = money + 2*(distance-3);
}
if (distance > 15 )
{
money = money + 2*12 + 3*(distance - 15);
}

return money;
}
public static void main(String args[]) {

System.out.println("請輸入公里數");
int distance_example=0;
Scanner key = new Scanner(System.in);
int n = key.nextInt();
distance_example = n;
Caculate pay = new Caculate();
pay.money = pay.charge(distance_example);
System.out.println("You need to pay money:"+pay.money+" distance is:"+distance_example);

}
}

5.
public class Test4
{

public static void main (String args[])
{
int n=100;
while(n<=1000)
{
int i,j,k;
i=n/100;
j=(n-i*100)/10;
k=n%10;
if((Math.pow(i, 3)+Math.pow(j, 3)+Math.pow(k, 3))==n)

System.out.print(n+String.valueOf('\t'));
n++;
}
}
}

6.
public class TestMoney
{
public static void main(String[] args)
{
int one=1,two=2,five=5;
for(int i=1;i<100;i++)
for(int j=1;j<50;j++)
for(int k=1;k<20;k++)
{
if((i*one+j*two+k*five)==100)
System.out.println(i+"個一分,"+j+"個兩分,"+k+"個五分");
}

}

}

7.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestJieCheng
{
public static void main (String args[])
{
int a=0,b=1;float sum=0;
System.out.print("請輸入要計算的階乘:");
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
a=Integer.parseInt(in.readLine());
}catch(IOException e){}
for(int i=1;i<=a;i++)
{
b=b*i;

}
System.out.print(a+"的階乘是"+b);
}
}

8.
public class Test4
{

public static void main (String args[])
{
int n=100;
while(n<=1000)
{
int i,j,k;
i=n/100;
j=(n-i*100)/10;
k=n%10;
if((Math.pow(i, 3)+Math.pow(j, 3)+Math.pow(k, 3))==n)

System.out.print(n+String.valueOf('\t'));
n++;
}
}
}

9.
public class TestNumber2
{
public static void main(String[] args)
{
final int maxline = 20;
double sum = 0;
double [] denominator = new double [maxline];
double [] numerator = new double [maxline];
for(int i=2;i<denominator.length;i++)
{
denominator[0]=1;
denominator[1]=2;
denominator[i]=denominator[i-1]+denominator[i-2];
}
for(int j=2;j<numerator.length;j++)
{
numerator[0]=2;
numerator[1]=3;
numerator[j]=numerator[j-1]+numerator[j-2];
}
for(int k=0;k<maxline;k++)
{
sum+=(numerator[k])/denominator[k];

}
System.out.println(sum);
}

}

10.
import java.io.*;

public class 根據輸入的三個數求一元二次方程
{
public static void main (String args[]) throws NumberFormatException, IOException
{
float a[]=new float [3];
for(int i=0;i<a.length;i++)
{
System.out.println("請輸入第"+(i+1)+"個數");
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
a[i]=Float.parseFloat(in.readLine());
}
float x1=0,x2=0;
x1=(float) ((((-1)*a[1])+(Math.sqrt(a[1]*a[1]-4*a[0]*a[2])))/(2*a[0]));
x2=(float) ((((-1)*a[1])-(Math.sqrt(a[1]*a[1]-4*a[0]*a[2])))/(2*a[0]));
System.out.print(a[0]+"X2"+a[1]+"X"+a[2]+"的兩個根是:");
System.out.print(x1+"和"+x2);
}
}

『肆』 JAVA編程題目,共四題,做其中一題就夠了,

好了,你測試一下咯!

public interface ShapeArea {//定義ShapeArea介面
public double getArea();//double getArea( ):求一個形狀的面積
public double getPerimeter();// Double getPerimeter( ):求一個形狀的周長。
}

public class MyTriangle implements ShapeArea {
double x,y,z,s;//x,y,z :double型,表示三角形的三條邊

public MyTriangle(double x, double y, double z) {//方法:MyTriangle(double x, double y, double z):構造函數,給三條邊和s賦值;
this.x = x;
this.y = y;
this.z = z;
this.s = (x+y+z)/2;
}

@Override
public double getArea() {
return Math.sqrt(this.s*(this.s-this.x)*(this.s-this.y)*(this.s-this.z));
}

@Override
public double getPerimeter() {
return (x+y+z);
}
@Override
public String toString() {
System.out.print("此三角形的面積和周長為:");
return this.getArea()+"、"+this.getPerimeter();
}

}

public class Test {//測試類
public static void main(String[] args) {
MyTriangle myTriangle = new MyTriangle(3, 4, 5);
System.out.println(myTriangle);
}

}

『伍』 5道簡單的JAVA編程題(高分懸賞)

很詳細的幫你寫下,呵呵,所以要給分哦!
1、
(1)源程序如下:
public class One {

public static void main(String[] args) {
String name = "張三";
int age = 23;
char sex = '男';
String myclass = "某某專業2班";
System.out.println("姓名:" + name);
System.out.println("姓名:" + age);
System.out.println("姓名:" + sex);
System.out.println("姓名:" + myclass);

}

}

(2)

編寫完程序的後綴名是.java,如本題,文件名就是One.java。
開始\運行\cmd,進入「命令提示符窗口」,然後用javac編譯器編譯.java文件,語句:javac One.java。

(3)
編譯成功後,生成的文件名後綴是.class,叫做位元組碼文件。再用java解釋器來運行改程序,語句:java One

2、編寫程序,輸出1到100間的所有偶數
(1)for語句
public class Two1 {

public static void main(String[] args) {
for(int i=2;i<=100;i+=2)
System.out.println(i);

}
}

(2)while語句
public class Two2 {

public static void main(String[] args) {
int i = 2;
while (i <= 100) {
System.out.println(i);
i += 2;
}
}
}

(3)do…while語句
public class Two3 {

public static void main(String[] args) {
int i = 2;
do {
System.out.println(i);
i += 2;
}while(i<=100);
}
}

3、編寫程序,從10個數當中找出最大值。
(1)for循環
import java.util.*;

public class Three1 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
for (int i = 0; i < 10; i++) {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
}
System.out.println("最大值:" + max);
}
}

(2)while語句
import java.util.*;

public class Three2 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int i = 0;
while (i < 10) {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
i++;
}
System.out.println("最大值:" + max);
}
}

(3)do…while語句
import java.util.*;

public class Three3 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int i = 0;
do {
System.out.print("輸入第" + (i + 1) + "個數:");
number = input.nextInt();
if (max < number)
max = number;
i++;
}while(i<10);
System.out.println("最大值:" + max);
}
}

4、編寫程序,計算從1到100之間的奇數之和。
(1)for循環

public class Four1 {

public static void main(String[] args) {
int sum=0;
for(int i = 1;i<=100;i+=2){
sum+=i;
}
System.out.println("1~100間奇數和:" + sum);
}
}

(2)while語句
public class Four2 {

public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i += 2;
}
System.out.println("1~100間奇數和:" + sum);
}
}

(3)do…while語句
public class Four3 {

public static void main(String[] args) {
int sum = 0;
int i = 1;
do {
sum += i;
i += 2;
} while (i <= 100);
System.out.println("1~100間奇數和:" + sum);
}
}

5、
(1)什麼是類的繼承?什麼是父類?什麼是子類?舉例說明。
繼承:是面向對象軟體技術當中的一個概念。如果一個類A繼承自另一個類B,就把這個A稱為"B的子類",而把B稱為"A的父類"。繼承可以使得子類具有父類的各種屬性和方法,而不需要再次編寫相同的代碼。在令子類繼承父類的同時,可以重新定義某些屬性,並重寫某些方法,即覆蓋父類的原有屬性和方法,使其獲得與父類不同的功能。另外,為子類追加新的屬性和方法也是常見的做法。繼承需要關鍵字extends。舉例:
class A{}
class B extends A{}
//成員我就不寫了,本例中,A是父類,B是子類。

(2)編寫一個繼承的程序。
class Person {
public String name;
public int age;
public char sex;

public Person(String n, int a, char s) {
name = n;
age = a;
sex = s;
}

public void output1() {
System.out.println("姓名:" + name + "\n年齡:" + age + "\n性別:" + sex);
}
}

class StudentPerson extends Person {
String school, department, subject, myclass;

public StudentPerson(String sc, String d, String su, String m, String n,
int a, char s) {
super(n, a, s);
school = sc;
department = d;
subject = su;
myclass = m;
}

public void output2() {
super.output1();
System.out.println("學校:" + school + "\n系別:" + department + "\n專業:"
+ subject + "\n班級:" + myclass);
}
}

public class Five2 {

public static void main(String[] args) {
StudentPerson StudentPersonDemo = new StudentPerson("某某大學", "某某系別",
" 某專業", "某某班級", " 張三", 23, '男');
StudentPersonDemo.output2();
}
}

『陸』 Java編程題,求解

// 上源碼

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {

/**
* 數字鍵 0-9鍵 *鍵 #鍵
*/
private static String[][] digits = new String[][]{
// 0
{},
// 1
{},
// 2
{"A", "B", "C"},
// 3
{"D", "E", "F"},
// 4
{"G", "H", "I"},
// 5
{"J", "K", "L"},
// 6
{"M", "N", "O"},
// 7
{"P", "Q", "R", "S"},
// 8
{"T", "U", "V"},
// 9
{"W", "X", "Y", "Z"},
// *
{},
// #
{},
};

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inputs;
String[] arr;
System.out.print("請輸入按鍵數字(多個數字空格隔開):");

while (null != (inputs = scanner.nextLine())) {
if ("exit".equalsIgnoreCase(inputs) || "quit".equalsIgnoreCase(inputs)) {
System.out.println("退出程序");
System.exit(1);
}
// 檢查args輸入參數是否合法
if (checkInput(inputs.split(" "))) {
arr = inputs.trim().split(" ");
// 查找輸入鍵的所有字母組合
List<String[]> inputCharList = new ArrayList<>();
for (String digit : arr) {
// *#01沒有字母
if ("*#01".indexOf(digit) >= 0) {
continue;
}
inputCharList.add(digits[Integer.parseInt(digit)]);
}

if (!inputCharList.isEmpty()) {
combineChars("", inputCharList);
System.out.println();
} else {
System.out.println("輸入的數字沒有字母組合。");
}
} else {
System.out.println("按鍵輸入不正確,請輸入0-9 * #鍵。");
}

System.out.print("請輸入按鍵數字(多個數字空格隔開):");
}
}

/**
* 遞歸查找所有字母組合
* @param headerChar
* @param inputCharList
*/
private static void combineChars(String headerChar, List<String[]> inputCharList) {
if (inputCharList.size() == 1) {
for (String ch : inputCharList.get(0)) {
System.out.print(headerChar + ch + " ");
}
} else {
for (String ch : inputCharList.get(0)) {
combineChars(headerChar + ch, inputCharList.subList(1, inputCharList.size()));
}
}
}

/**
* 校驗輸入是否合法
*
* @param args
* @return
*/
static boolean checkInput(String[] args) {
String validInputs = "0123456789*#";
boolean isValid = true;

for (String arg : args) {
if (arg.length() != 1 || validInputs.indexOf(arg) < 0) {
isValid = false;
break;
}
}

return isValid;
}

}


運行效果

題目里只說了輸入兩個數字的情況,輸入* # 1 0這里我直接視為無效輸入了(忽略掉了),對於輸入超過兩個數字以上的情況也能按要求輸出。(考慮到輸入的數字個數不確定因素,這里用到了遞歸,如果確定只有1或2個數字輸入,代碼會簡介很多,也不需要遞歸)

『柒』 Java的編程題目,在線等,急急急

先做兩個比較簡單的先用:
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Function {
/**
* 設計一個方法,完成字元串的解析。方法定義為:public void myParseString(String inputStr);
* 對於給定的字元串,取得字元串內的各個整數(不考慮小數,),然後將取得的數排序,按從小到大依次列印出來。
* @param args
*/
public static void main(String[] args) {
String s = "aa789bB22cc345dd;5.a";
new Function().myParseString(s);
}
public void myParseString(String inputStr){
String mathregix="\\d+";//數字
Vector vector=new Vector();
Pattern fun=Pattern.compile(mathregix);
Matcher match = fun.matcher(inputStr);
while (match.find()) {
vector.add(match.group(0));
}
Object[] obj=vector.toArray();
int[] result=new int[obj.length];

for (int i = 0; i < obj.length; i++) {
result[i]=Integer.parseInt((String) obj[i]);
}
Arrays.sort(result);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}

import java.util.Date;
/**
* 有一個學生類(Student),其有四個私有屬性,分別為:
* 學號no,字元串型;
* 姓名name,字元串型;
* 年齡age,整型;
* 生日birthday,日期型;
* 請:
* 1) 按上面描述設計類;
* 2) 定義對每個屬性進行取值,賦值的方法;
* 3) 要求學號不能為空,則學號的長度不能少於5位字元,否則拋異常;
* 4) 年齡范圍必須在[1,500]之間,否則拋出異常;
*/
public class Student {
private String no;
private String name;
private int age;
private Date birthday;
public int getAge() {
return age;
}
public void setAge(int age) throws Exception {
if(age<1||age<500)throw new Exception("年齡不合法。");
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) throws Exception {
if(no==null)throw new Exception("學號不能為空!");
if(no.length()<5)throw new Exception("學號不能少於五位!");
this.no = no;
}
}

二、三題
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

/**
* 2. 設計一個GUI界面,要求打界面如下:
*點擊文件->打開,打開文件選擇器,選擇打開給定的java.txt文件,將文件內所有a-z,A-Z之間的字元顯示在界面的文本區域內。
* 3. 設置一個GUI界面,界面如下:
* 點擊文件->保存,打開文件選擇窗體,選擇一個保存路徑,將本界面文本區域內輸入的內容進行過濾,將所有非a-z,A-Z之間的字元保存到C盤下的java.txt文件內。
* Java.txt文件內容如下:
* 我們在2009年第2學期學習Java Programming Design,於2009-6-16考試。
*
*
*
*/
public class FileEditer extends javax.swing.JFrame implements ActionListener {
private JMenuBar menubar;
private JMenu file;
private JMenuItem open;
private JTextArea area;
private JMenuItem save;
private JFileChooser jfc;

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FileEditer inst = new FileEditer();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}

public FileEditer() {
super();
initGUI();
}

private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
area = new JTextArea();
getContentPane().add(area, BorderLayout.CENTER);
area.setText("文本區");
}
{
menubar = new JMenuBar();
setJMenuBar(menubar);
{
file = new JMenu();
menubar.add(file);
file.setText("文件");
file.setPreferredSize(new java.awt.Dimension(66, 21));
{
open = new JMenuItem();
file.add(open);
open.setText("打開");
open.setBorderPainted(false);
open.setActionCommand("open");
open.addActionListener(this);
}
{
save = new JMenuItem();
file.add(save);
save.setActionCommand("save");
save.setText("保存");
save.addActionListener(this);
}
}
}
{
jfc=new JFileChooser();
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent e) {
if("open".equals(e.getActionCommand())){
int result=jfc.showOpenDialog(this);
if(result==jfc.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
byte[] b=new byte[1024];
FileInputStream fis=new FileInputStream(file);
fis.read(b);
fis.close();
String string=new String(b,"GBK");
string=string.replaceAll("[^a-zA-Z]*", "");
area.setText(string.trim());
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}

}
}else if("save".equals(e.getActionCommand())){
int result=jfc.showSaveDialog(this);
if(result!=jfc.APPROVE_OPTION)return;
File file=jfc.getSelectedFile();
try {
if(!file.exists()){
file.createNewFile();
}
String string = area.getText();
string=string.replaceAll("[a-zA-Z]*", "");
byte[] b=string.getBytes();
FileOutputStream fis=new FileOutputStream(file);
fis.write(b);
fis.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}

}
}

}

『捌』 java編程題 希望大家能夠幫助我一下,謝謝

package book;

/**

* @Author: Cool_Wu

* @Date: 2020-12-07 20:18

*/

public class Book {

private String name;

private String num;

private String author;

private double price;

private String publishing_House;

private String publication_Date;

public Book() {}

public Book(String name, String num, String author, double price, String publishing_House, String publication_Date) {

this.name = name;

this.num = num;

this.author = author;

this.price = price;

this.publishing_House = publishing_House;

this.publication_Date = publication_Date;

}

@Override

public String toString() {

return "圖書信息: ----------------------" +

" 書名:" + name +

" 書號:" + num +

" 作者:" + author +

" 單價:" + price +

" 出版社:" + publishing_House +

" 出版日期:" + publication_Date +

" ---------------------- ";

}

}


package book;

public class Test {

public static void main(String[] args) {

Book book1 = new Book("百年孤獨","10000","加西亞·馬爾克斯",40.00,"南海出版公司","2017年08月");

System.out.println(book1);

Book book2 = new Book("時間簡史","10086","史蒂芬·霍金",22.50,"湖南科技出版社","2014年06月");

System.out.println(book2);

}

}


運行結果

『玖』 JAVA編程的幾個簡單題目

第一個:
import java.util.Scanner;
import java.util.*;
public class Validate
{
private int n;
/*count_6、count_7、count_8 用來記錄收斂那個數字的個數,在這里我記錄只要他出現了10次我就認為他收斂與他了
* 還沒想到更好的辦法,如果不設置這個,就會出現棧溢出,遞歸不出來了!不過可以看到結果輸出結果確實是對的
*/
private int count_6;
private int count_7;
private int count_8;
private Stack<Integer> stack= new Stack<Integer>();//棧用來存放素因子
public void scan()
{
Scanner scan = new Scanner(System.in);
try{
n = scan.nextInt();
}catch(NumberFormatException ne){
System.out.println(ne.getMessage());
}
}

public boolean isPrime(int n)
{
if(n>2 && 0 == n%2)//是大於2偶數
{
return false;

}else{

for(int i=3; i<n; i +=2)
{
if(0 == n%i)
return false;
}
return true;
}
}

public void analyze(int n)
{
if(isPrime(n))
{
stack.push(n);
return;
}
if(0 == n%2){
stack.push(2);
n = n/2;
analyze(n);
}else{

for(int i=3; i<n; i +=2)
{
if(isPrime(i)&& 0 == n%i)
{
stack.push(i);
n = n/i;
analyze(n);
}
}

}
}

public void mySort()
{
check(n);
}
public void check(int m)
{
if(isPrime(m)){
m++;
}
else{
analyze(m);
m = 0;
while(!stack.empty())
{
int k = stack.pop().intValue();
m += k;
}
stack.clear();
m++;
}
if(m == 6 || m == 7 || m == 8)
{
if(6 == m)
{
count_6++;
System.out.println("m = " + m);
}else if(7 == m){
count_7++;
System.out.println("m = " + m);
}else if(8 == m){
count_8++;
System.out.println("m = " + m);
}
}
if(count_6 > 10 || count_7 > 10 || count_8 > 10)
{
return;
}
check(m);
}

public static void main(String[] args)
{
Validate v = new Validate();
v.scan();
v.mySort();
}
}

第二個:
import java.util.Scanner;

class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}

public class MyExceptionTest {

public int scan()
{
int a = 0;
Scanner scan = new Scanner(System.in);
try{
a = scan.nextInt();
}catch(NumberFormatException ne){
System.out.println(ne.getMessage());
}
return a;
}

public int cal(int a, int b) throws MyException
{
if(b==0) throw new MyException("自定義異常: 輸入的第二個數為0");
else if(a/b<1) throw new MyException("自定義異常: 相除的結果小於1");
else return a/b;

}
public static void main(String[] args) {

MyExceptionTest me = new MyExceptionTest();
System.out.print("請輸入第一個數:");
int a = me.scan();
System.out.print("請輸入第二個數:");
int b = me.scan();
try{
System.out.println("相除的結果:" + me.cal(a, b));
}catch(MyException e){
System.out.println(e.getMessage());
}
}

}

第三個:
import java.util.*;
import java.util.Map.Entry;

public class CountCharacter {

private static Map<String, Integer> map = new LinkedHashMap<String, Integer>();

private static final int ONE = 1 ; //沒有出現過,則設置其出現一次;

private String content = null;

public void scan()
{
Scanner scan = new Scanner(System.in);
content = scan.nextLine();
}

public void count()
{
String [] text = content.split(" ");
for(int i=0; i<text.length; i++)
{
if (!map.containsKey(text[i])) {
map.put(text[i], ONE);
} else {
int value = map.get(text[i]);
map.put(text[i], value + 1);
}
}
}
public <K, V extends Number> Map<String, V> sortMap(Map<String, V> map) {
class MyMap<M, N> {
private M key;
private N value;
private M getKey() {
return key;
}
private void setKey(M key) {
this.key = key;
}
private N getValue() {
return value;
}
private void setValue(N value) {
this.value = value;
}
}

List<MyMap<String, V>> list = new ArrayList<MyMap<String, V>>();
for (Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
MyMap<String, V> my = new MyMap<String, V>();
String key = i.next();
my.setKey(key);
my.setValue(map.get(key));
list.add(my);
}

Collections.sort(list, new Comparator<MyMap<String, V>>() {
public int compare(MyMap<String, V> o1, MyMap<String, V> o2) {
if(o1.getValue().equals(o2.getValue())) {
return o1.getKey().compareTo(o2.getKey());
}else{
return (int)(o2.getValue().doubleValue() - o1.getValue().doubleValue());
}
}
});

Map<String, V> sortMap = new LinkedHashMap<String, V>();
for(int i = 0, k = list.size(); i < k; i++) {
MyMap<String, V> my = list.get(i);
sortMap.put(my.getKey(), my.getValue());
}
return sortMap;
}

public static void main(String[] args) {
CountCharacter cc = new CountCharacter();
cc.scan();
cc.count();
Map<String, Integer> sortMap = cc.sortMap(cc.map);

Iterator<Entry<String, Integer>> it = sortMap.entrySet().iterator();
Map.Entry<String,Integer> entry = null;
int i=0;
while(it.hasNext()&& i<10) {//去前面10個
i++;
entry = (Entry<String,Integer>) it.next();
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
}

}

第四個:
import java.util.Scanner;
public class IntegerShape{
public static void main(String[] args){
double a = 0;
int b = 0;
Scanner in = null;
do{
try{
System.out.print("請輸入一個的數:");
in=new Scanner(System.in);
a=in.nextFloat();
break;
}catch(Exception ne){
System.out.println("輸入數據錯誤!");
}
}while(true);
do{
try{
System.out.print("請輸入顯示的行數:");
in=new Scanner(System.in);
b=in.nextInt();
break;
}catch(Exception ne){
System.out.println("輸入數據錯誤!");
}
}while(true);
for(int i=b;i>0;i--)
{
System.out.println(a);
a=a/2;
}
}
}
第五個:
import java.util.Scanner;
import java.util.Vector;

public class MyVector {

private Vector<String> vectorStr = new Vector<String>(); //用來方單詞
private Vector<Integer> vectorInt = new Vector<Integer>();//用來記錄對應下標的單詞的個數
private static final int ONE = 1 ; //沒有出現過,則設置其出現一次;

private String content = null;

public void scan()
{
Scanner scan = new Scanner(System.in);
content = scan.nextLine();
}

public void countWord()
{
int index = -1;
String [] text = content.split(" ");
for(int i=0; i<text.length; i++)
{
if(vectorStr.contains(text[i])){ //若次單詞已經存在與vector中則只要修改對應的個數
index = vectorStr.indexOf(text[i]);
int value = vectorInt.get(index)+1;
vectorInt.setElementAt(value, index);
}
else{//若不存在則添加該單詞,同時要初始化對應下標的單詞的個數
vectorStr.add(text[i]);
vectorInt.add(ONE);
}
}
System.out.println(vectorStr);
}

public void display()
{
for(int i=0; i<vectorStr.size(); i++)
{
System.out.println(vectorStr.get(i) + "->" + vectorInt.get(i));
}
}
public static void main(String[] args) {

MyVector mv = new MyVector();
mv.scan();
mv.countWord();
mv.display();
}
}

最後一個了不容易!考慮加點分吧!

import java.util.*;
public class Exp {

private int integer;
private boolean bool = false;
private Stack<Integer> stack = new Stack<Integer>();

public void scan()
{
System.out.print("輸入一個整數:");
Scanner scan = new Scanner(System.in);
while(true){
try{
integer = scan.nextInt();
break;
}catch(Exception e){
System.out.println("輸入錯誤!");
}
}
}

public void operation()
{

for(int i=1; i<integer; i++)
{
int sum = 0;
for(int j = i; j<=integer; j++)
{
stack.push(j);
sum += j;
if(sum == integer)
{
int k = 0, n = stack.size();
bool = true;
System.out.print(integer + " = ");
while(!stack.empty())
{
k++;
if(k<n)
{
System.out.print(stack.pop().intValue() + " + ");
}
else
{
System.out.print(stack.pop().intValue() + "\n");
}
}
stack.clear();
}else if(sum > integer){
stack.clear();
}
}
}
if(!bool)
System.out.println("該整數沒有連續正整數序列!");
}
public static void main(String[] args) {
Exp e = new Exp();
e.scan();
e.operation();
}

}

以上運行過了可以!

熱點內容
循跡小車演算法 發布:2024-12-22 22:28:41 瀏覽:82
scss一次編譯一直生成隨機數 發布:2024-12-22 22:04:24 瀏覽:956
嫁接睫毛加密 發布:2024-12-22 21:50:12 瀏覽:975
linuxbin文件的安裝 發布:2024-12-22 21:46:07 瀏覽:798
vlcforandroid下載 發布:2024-12-22 21:45:26 瀏覽:664
電腦做網關把數據發送至伺服器 發布:2024-12-22 21:44:50 瀏覽:432
新華三代理什麼牌子的伺服器 發布:2024-12-22 21:33:21 瀏覽:342
歡太會員密碼是什麼 發布:2024-12-22 20:57:28 瀏覽:74
sqllocaldb 發布:2024-12-22 20:07:08 瀏覽:127
如何找到我的伺服器 發布:2024-12-22 19:52:14 瀏覽:301