java编程练习题
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();
}
}
以上运行过了可以!