(找出最大的对象)编写一个方法,返回对象数组中最大的对象。方法签名如下: public static Object max(Comparable[] a) public static Object max(Comparable[] a)
import java.util.*; public class Main{ public static Object max(Comparable[] a) { /// 请填写此部分内容 }
public static void main(String[] args){
String[] sArray = new String[5];
Integer[] intArray = new Integer[5];
Scanner input = new Scanner(System.in);
for(int i=0;i
}
所有对象都是Comparable接口的实例。对象在数组中的顺序是由compareTo方法决定的。 编写测试程序,从键盘输入5个字符串和5个整数,创建一个由5个字符串构成的数组、一个由5个整数构成的数组。找出数组中最大的字符串、整数并输出。
请在这里描述输出格式。例如:对每一组输入,在一行中输出A+B的值。
在这里给出一组输入。例如:
Xi'an (输入5个字符串,每行一个)
Beijing
ShangHai
GuangZhou
ShenZhen
8 9 12 7 6 (输入5个整数,以空格分隔)
在这里给出相应的输出。例如:
Max string is Xi'an (输出最大的字符串)
Max integer is 12 (输出最大的整数)
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] s=new String[5];
for (int i = 0; i < 5; i++) {
String a=input.next();
s[i]=a;
}
int[] b=new int[5];
for (int i = 0; i < 5; i++) {
int a=input.nextInt();
b[i]=a;
}
Arrays.sort(s);
System.out.println("Max string is "+s[4]);
Arrays.sort(b);
System.out.print("Max integer is "+b[4]);
}
}
Xi’an
Beijing
ShangHai
GuangZhou
ShenZhen
8 9 12 7 6
文件phonebook1.txt中有若干联系人的姓名和电话号码。 高富帅 13312342222 白富美 13412343333 孙悟空 13512345555 唐三藏 13612346666 猪悟能 13712347777 沙悟净 13812348888 请你编写一个简单的通信录程序,当从键盘输入一个姓名时查找到对应的电话号码并输出。如果没找到则显示Not found. 由于目前的自动裁判系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的姓名和电话号码,当输入的名字为noname时,表示结束。noname后面有一个名字,需要查找其对应的电话号码。
高富帅 13312342222 白富美 13412343333 孙悟空 13512345555 唐三藏 13612346666 猪悟能 13712347777 沙悟净 13812348888 noname (表示结束) 唐三藏 (需要查找此人的电话号码)
13612346666 (输出对应的电话号码)
白富美 13412343333
孙悟空 13512345555
唐三藏 13612346666
猪悟能 13712347777
沙悟净 13812348888
noname
白骨精
Not found.
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
HashMap<String, String> telephone = new HashMap<>();
while (true) {
telephone.put(input.next(), input.next());
if(telephone.get("noname")!=null) {
break;
}
}
String man =telephone.get("noname");
if(telephone.get(man)!=null) {
System.out.println(telephone.get(man));
}
else {
System.out.println("Not found.");
}
input.close();
}
}
Write a method that finds the number of occurrences of a specified character in the string using the following header: public static int count(String str, char a) For example, count(“Welcome”, ‘e’) returns 2. Write a test program that prompts the user to enter a string followed by a character and displays the number of occurrences of the character in the string.
please input the string and the character.
Then output the the number of occurrences of a specified character in the string.
Welcome e
The number of occurrences is 2.
import java.util.Scanner;
public class Main {
static public void main(String []args)
{
Scanner scan = new Scanner(System.in); //System.in.read(a);
String a = scan.next();
String b = scan.next();
char[] c=a.toCharArray();
char[] d =b.toCharArray();
int count=0;
for(int i=0;i<a.length();i++)
{
if(c[i]==d[0])
{
count++;
}
}
System.out.print("The number of occurrences is "+count+".");
scan.close();
}
}
给定两个字符串,求解给定字符串的后缀。按照如下的格式进行输出
输入为一对字符串,以空格分开。 例如:
father mather
返回两个字符串的最大后缀,例如:
The common suffix is ather.
又如:
Tom Jack
No common suffix.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
StringBuilder s1=new StringBuilder(sc.next());
StringBuilder s2=new StringBuilder(sc.next());
StringBuilder s=new StringBuilder();
int len;
if(s1.length()<s2.length())
len=s1.length();
else len=s2.length();
s2=s2.reverse();
s1=s1.reverse();
for(int i=0;i<len;++i)
if (s2.charAt(i)==s1.charAt(i)) {
s.append(s1.charAt(i));
} else break;
if(0 == s.length())
System.out.println("No common suffix.");
else
System.out.println("The common suffix is "+s.reverse()+".");
sc.close();
}
}
Write a program that prompts the user to entern three points (x1,y1),(x2,y2), (x3,y3) of a triangle and displays its area. The formula for computing the area of a triangle is s = (side1 + side2 + side3)/2; area = Math.sqrt(s (s - side1) (s - side2) (s - side3));
Enter three points for a triangle,there is a space among the values. i.e : 1.5 -3.4 4.6 5 9.5 -3.4
Output the area. Keep the two decimal places. i.e : The area of the triangle is 33.60.
1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.60.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
double x3 = sc.nextDouble();
double y3 = sc.nextDouble();
double side1 = Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
double side2 = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
double side3 = Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
double s = (side1+side2+side3)/2;
double area = Math.sqrt(s*(s - side1)*(s - side2)*(s - side3));
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("The area of the triangle is "+df.format(area)+".");
sc.close();
}
}
(Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to measure the coldness using temperature and wind speed. The formula is given as follows: windCold = 35.74 + 0.6215 x fahrenheit - 35.75 x Math.pow(speed, 0.16) + 0.4275 x fahrenheit x Math.pow(speed, 0.16);
Enter three value for the Fahrenheit and wind speed miles per hour.
Output the wind chill index.
5.3
6
The wind chill index is -5.56707
import java.util.Scanner;
import java.lang.Math;
//import java.text.DecimalFormat;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
double fahrenheit = Input.nextDouble();
double speed = Input.nextDouble();
double WindCold = 35.74 + 0.6215 * fahrenheit - 35.75 * Math.pow(speed, 0.16) + 0.4275 * fahrenheit * Math.pow(speed, 0.16);
System.out.println("The wind chill index is " +WindCold);
Input.close();
}
}
(Palindrome integer) Write the following two methods//Return the reversal of an integer, i.e. reverse(456) returns 654 public static int reverse(int number) Return true if number is palindrome public static boolean isPalindrome(int number) Use the reverse method to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts theuser to enter an integer and reports whether the integer is a palindrome.
Enter one int number.
Displays whether the integer is a palindrome.
1214344232
1214344232 is NOT a palindrome.
123454321
123454321 is a palindrome.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
//System.out.print("Enter an integer: ");
int n = input.nextInt();
if(isPalindrome(n) == true)
System.out.println(n + " is a palindrome.");
else
System.out.println(n + " is NOT a palindrome.");
}
public static int reverse(int number) {
int temp = 0;
for(; number != 0; ) {
temp *= 10;
temp += number % 10;
number /= 10;
}
return temp;
}
public static boolean isPalindrome(int number) {
if(number == reverse(number))
return true;
else
return false;
}
}
(Count the letters in a string) Write a method that counts the number of letters in a string using the following header: public static int countLetters(String s) Write a test program that prompts the user to enter a string and displays the number of letters in the string.
Enter a string
Displays the number of the letters in the string.
qwe&&&,,;#@23qer
The number of letters inside the string is: 6
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
String str = Input.nextLine();
char[] ch_str = str.toCharArray();
int count=0;
for(int i=0; i<str.length(); i++)
if( (ch_str[i]>='a' && ch_str[i] <= 'z') || (ch_str[i]>='A' && ch_str[i] <= 'Z'))
count++;
System.out.print("The number of letters inside the string is: "+count);
Input.close();
}
}
(Convert milliseconds to hours, minutes, and seconds) Write a method that converts milliseconds to hours, minutes, and seconds using the following header: public static String convertMillis(long millis) The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10
Enter a long
Displays the time with the format xx:xx:xx.
5500
0:0:5
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
public static void main(String[] args){
long ms;
Scanner input = new Scanner(System.in);
ms = input.nextLong();
long hou = 0, min = 0, sec = 0;
sec = ms/1000;
if(sec >= 60) {
min = sec/60;
sec = sec%60;
}
if(min >= 60) {
hou = min/60;
min = min%60;
}
System.out.println(hou + ":" + min + ":" + sec);
input.close();
}
}
(Geometry: intersecting point) Suppose two line segments intersect. The two end-points for the first line segment are (x1, y1) and (x2, y2) and for the second line segment are (x3, y3) and (x4, y4).Write a program that prompts the user to enter these four endpoints and displays the intersecting point. the intersecting point can be found by solving a linear equation. Write the LinearEquation class in Programming to solve this equation.
Enter eight double number
Displays the intersecting point or The two lines are parallel .
2.3 4.5 6.7 -3.4 4 5.6 6.7 9.1
The intersecting point is at (2.6569833923223523, 3.859052545603048)
1 2 3 4 5 6 7 8
The two lines are parallel
import java.util.*;
public class Main {
public static void main(String[] args) {
double x1, y1, x2, y2, x3, y3, x4, y4;
double a, b, c, d, e, f, x, y, discriminant;
//System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4: ");
Scanner input = new Scanner(System.in);
x1 = input.nextDouble(); y1 = input.nextDouble();
x2 = input.nextDouble(); y2 = input.nextDouble();
x3 = input.nextDouble(); y3 = input.nextDouble();
x4 = input.nextDouble(); y4 = input.nextDouble();
a = y1 - y2;
b = x2 - x1;
c = y3 - y4;
d = x4 - x3;
e = a * x1 + b * y1;
f = c * x3 + d * y3;
discriminant = a * d - b * c;
if(discriminant != 0)
{
x = (e * d - b * f) / discriminant;
y = (a * f - e * c) / discriminant;
System.out.println("The intersecting point is at (" + x + ", " + y + ")");
}
else
System.out.println("The two lines are parallel");
input.close();
}
}
(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as a double type. Write the following method that returns the location of the largest element in a two-dimensional array: public static Location locateLargest(double[][] a) The return value is an instance of Location.Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array.
Enter the row and column and the number in the array. For example: 2 3 234 223 444 111 343 454
displays the location of the largest element in the array. Such as : e location of the largest element is 454.0 at (1, 2)
2 3
234 223 444
111 343 454
The location of the largest element is 454.0 at (1, 2)
import java.util.*;
class Location{
public int row = 0;
public int column = 0;
public double maxValue = 0;
Location(){}
}
public class Main {
public static Location locateLargest(double [] [] a) {
Location b = new Location();
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
{
if(b.maxValue<a[i][j])
{
b.maxValue = a[i][j];
b.row = i;
b.column = j;
}
}
return b;
}
public static void main(String[] args) {
Location q = new Location();
Scanner in = new Scanner(System.in);
int w = in.nextInt();
int e = in.nextInt();
double[][] a = new double[w][e];
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
{
a[i][j] = in.nextDouble();
}
q = locateLargest(a);
//System.out.printf("The location of the largest element is %.1f at (%d, %d)\n",q.maxValue,q.row,q.column);
System.out.println("The location of the largest element is "+q.maxValue+" at ("+q.row+", "+q.column+")");
in.close();
}
}
(Combine two lists then sorted it.)
Write a method that returns the union of two array lists of integers using the following header:
public static ArrayList union( ArrayList list1, ArrayList list2)
For example, the union of two array lists {2,3,1,5} and {3,4,6} is {2, 3, 1, 5, 3, 4, 6}.
Write a test program that prompts the user to enter two lists, then sorted the union list, finally displays their sorted union. The numbers are separated by exactly one space in the output.
Write a test program that prompts the user to enter the two number m,n for the length of two arrays in the first line, and the next two line input m integer and n intergers for the two array. After sort theunion intergers and displays the sorted union list separated by exactly one space.
Input the two number m,n for the length of two arrays in the first line, and the next two line input m integer and n intergers .
Displays the sorted union list separated by exactly one space…
3 4
23 44 32
12 43 32 44
12 23 32 32 43 44 44
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt()+input.nextInt();
int[] num=new int[n];
for(int i=0;i<n;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
for(int i=0;i<n;i++) {
System.out.print(num[i]+" ");
}
input.close();
}
}
(Geometry: intersecting point) Suppose two line segments intersect. The two end-points for the first line segment are (x1, y1) and (x2, y2) and for the second line segment are (x3, y3) and (x4, y4).Write a program that prompts the user to enter these four endpoints and displays the intersecting point. the intersecting point can be found by solving a linear equation. Write the LinearEquation class in Programming to solve this equation. You need to keep the last three decimal places. (你需要保留小数点后三位)
Enter eight double number
Displays the intersecting point or The two lines are parallel .
2.3 4.5 6.7 -3.4 4 5.6 6.7 9.1
The intersecting point is at (2.657,3.859)
1 2 3 4 5 6 7 8
The two lines are parallel
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
double x1,x2,x3,x4,y1,y2,y3,y4;
double a,b,c,d,e,f,x,y,t;
DecimalFormat num = new DecimalFormat("#.000");
Scanner input = new Scanner(System.in);
x1=input.nextDouble();
y1=input.nextDouble();
x2=input.nextDouble();
y2=input.nextDouble();
x3=input.nextDouble();
y3=input.nextDouble();
x4=input.nextDouble();
y4=input.nextDouble();
a=y1-y2;
b=x2-x1;
c=y3-y4;
d=x4-x3;
e=a*x1+b*y1;
f=c*x3+d*y3;
t=a*d-b*c;
if(t!=0) {
x=(e*d-b*f)/t;
y=(a*f-e*c)/t;
System.out.println("The intersecting point is at ("+num.format(x)+","+num.format(y)+")");
}
else {
System.out.println("The two lines are parallel");
}
input.close();
}
}
定义一个名为Stock的股票类,这个类包括:一个名为symbol的字符串数据域表示股票代码。一个名为name的字符串数据域表示股票名称。一个名为previousClosingPrice的double数据域,它存储前一日的股票交易价格。一个名为currentPrice数据域,它存储当前的股票交易价格。创建一个有特定代码和名称的股票的构造方法。一个名为changePercent()方法返回从previousClosingPrice变化到currentPrice的百分比。 ###类名为:
Stock
import java.util.Scanner;
/* 你提交的代码将被嵌入到这里 */
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String symbol1=input.next();
String name1=input.next();
Stock stock = new Stock(symbol1, name1);
stock.previousClosingPrice = input.nextDouble();
// Input current price
stock.currentPrice = input.nextDouble();
// Display stock info
System.out.println(stock.name+"price changed: " + stock.changePercent() * 100 + "%");
input.close();
}
}
002594
比亚迪
56.98
55.40
比亚迪股价涨跌: -2.77290277290277%
class Stock
{
String symbol;
String name;
double previousClosingPrice;
double currentPrice;
public Stock(String s,String n)
{
symbol=s;name=n;
}
public double changePercent()
{
return -(previousClosingPrice-currentPrice)/previousClosingPrice;
}
}
创建一个正六边形(regular hexagon)RHexagon类,实现下列接口IShape。RHexagon类将正六边形的边长作为私有成员,类中包含初始化这个值的构造方法。
interface IShape {// 接口
double getArea(); // 求面积
double getPerimeter();// 求周长
}
请编程从键盘输入正六边形的边长值,创建一个正六边形对象,然后输出正六边形的面积和周长。保留4位小数。
正六边形类名:
RHexagon
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
double getArea();
double getPerimeter();
}
//你提交的代码将被嵌入到这里public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
IShape r = new RHexagon (a);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
输入
16.8 (边长)
输出
733.281 (输出的面积)
100.8 (输出的周长)
5
64.9519
30
class RHexagon implements IShape{
private double a;
public RHexagon(double a) {
super();
this.a = a;
}
public double getArea() {
return (3 * Math.sqrt(3)) / 2 * a * a;
}
public double getPerimeter() {
return (a*6);
}
}
将学生对象按照成绩降序排序 (10分)
请阅读程序并补全源代码:先从键盘录入5个学生的数据,保存到容器对象ar中,然后按照成绩score从高到低排序之后输出。
import java.util.*;
class Student {
String number;
String name;
float score;
// Constructor
Student(String number1, String name1, float score1) {
number = number1;
name = name1;
score = score1;
}
// Used to print student details in main()public String toString() {
return this.number + " " + this.name + " " + this.score;
}
}
public class Main {
public static void main(String[] args) {
ArrayList ar = new ArrayList();
/* 请在这里补全代码,使程序完成指定的功能。 */
在这里输入5个学生的记录:
04031021 张三 84
04031013 李四 73
04031018 王五 98
04031038 马六 65
04031029 陈七 96
04031018 王五 98.0
04031029 陈七 96.0
04031021 张三 84.0
04031013 李四 73.0
04031038 马六 65.0
Scanner sc=new Scanner(System.in);
int n=0;
String num;
String name;
float score;
for(int i=0;i<5;i++) {
Student s = new Student(sc.next(), sc.next(), sc.nextFloat());
ar.add(s);
}
ar.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return (int)(o2.score-o1.score);
//升序只需要return (int)(o1.score-o2.score);
}
});
for(Student elem:ar)
System.out.println(elem.toString());
sc.close();
}
}
给定一元二次方程的系数,求一元二次方程的根。简便起见,不要求是复根,而且相等的根只输出一个解。注意判断浮点数为零与否用|x|<10e-6来判断。要求可以重复输入输出。要求结果保留小数点后两位数字。 输入输出形式范例: 输入样例1: 1 2 1 输出样例1:The root is:-1.00. 输入样例2: 1 2 -1 输出样例2: The roots are 0.41 and -2.41. 输入样例3: 1 2 2 输出样例3: The equation has no real roots.
输入一组一元二次方程的系数
输出一元二次方程的根
1 2 1
The root is:-1.00.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int a, b, c;
a = reader.nextInt();
b = reader.nextInt();
c = reader.nextInt();
DecimalFormat df = new DecimalFormat("0.00");
int delta;
double x1, x2;
delta = b * b - 4 * a * c;
if(a==0 && b==0 && c==0) {
System.out.println("The equation has no real roots.");
return;
}
if(a==0 && b==0 && c!=0) {
System.out.println("The equation has no real roots.");
return;
}
if(delta == 0) {
x1 = b / (-2.0 * a);
x2 = b / (-2.0 * a);
System.out.println("The root is:"+df.format(x1)+".");
}
if(delta > 0) {
x1 = (-b + Math.sqrt(delta)) / (2.0 * a);
x2 = (-b - Math.sqrt(delta)) / (2.0 * a);
System.out.println("The roots are "+df.format(x1)+" and "+df.format(x2)+".");
}
if(delta < 0) {
System.out.println("The equation has no real roots.");
//return;
}
}
}
(Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to measure the coldness using temperature and wind speed. The formula is given as follows: windCold = 35.74 + 0.6215 x fahrenheit - 35.75 x Math.pow(speed, 0.16) + 0.4275 x fahrenheit x Math.pow(speed, 0.16);
Enter three value for the Fahrenheit and wind speed miles per hour.
Output the wind chill index.
5.3
6
The wind chill index is -5.56707
import java.util.Scanner;
import java.lang.Math;
//import java.text.DecimalFormat;
public class Main
{
public static void main(String[] args)
{
// DecimalFormat decimalFormat = new DecimalFormat("#.00000");
Scanner Input = new Scanner(System.in);
double fahrenheit = Input.nextDouble();
double speed = Input.nextDouble();
double WindCold = 35.74 + 0.6215 * fahrenheit - 35.75 * Math.pow(speed, 0.16) + 0.4275 * fahrenheit * Math.pow(speed, 0.16);
System.out.println("The wind chill index is " +WindCold);
//System.out.println("The wind chill index is " + decimalFormat.format(WindCold));
Input.close();
}
}
给定一个字符串,对该字符串进行排序,请输出排好序的字符串。要求能够连续输入输出的字符串。
在一行输入一个字符串
输出排好序的字符串的序列
fecbad
abcdef
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
char [] a = str.toCharArray();
for(int i = 0; i <str.length(); i++) {
for(int j = i+1; j < str.length(); j++) {
if(a[j] < a[i]) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
str = String.valueOf(a);
System.out.println(str);
}
}
(Convert milliseconds to hours, minutes, and seconds) Write a method that converts milliseconds to hours, minutes, and seconds using the following header: public static String convertMillis(long millis) The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10
Enter a long
Displays the time with the format xx:xx:xx.
5500
0:0:5
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
public static void main(String[] args){
long ms;
Scanner input = new Scanner(System.in);
ms = input.nextLong();
long hou = 0, min = 0, sec = 0;
sec = ms/1000;
if(sec >= 60) {
min = sec/60;
sec = sec%60;
}
if(min >= 60) {
hou = min/60;
min = min%60;
}
System.out.println(hou + ":" + min + ":" + sec);
input.close();
}
}
(Business: check ISBN-10) An ISBN-10 (International Standard Book Number) consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, which is calculated from the other nine digits using the following formula: (d1 x 1 + d2 x 2 + d3 x3 + d4 x 4 + d5 x5 + d6 x 6 + d7 x 7+ d8 x 8 + d9 x 9 ) % 11 If the checksum is 10, the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer.
Enter the first 9 digits
Displays the 10-digit ISBN.
123456789
The ISBN-10 number is 123456789X
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = input.next();
int d10 = ((s.charAt(0) - '0') + (s.charAt(1) - '0')*2 + (s.charAt(2) - '0')*3 + (s.charAt(3) - '0')*4
+ (s.charAt(4) - '0')*5 + (s.charAt(5) - '0')*6 + (s.charAt(6) - '0')*7 + (s.charAt(7) - '0')*8
+ (s.charAt(8) - '0')*9) % 11;
if(d10 == 10)
System.out.println("The ISBN-10 number is " + s + "X");
else
System.out.println("The ISBN-10 number is " + s + d10);
input.close();
}
}
使用公历类 GregorianCalendar,公历类 GregorianCalendar有方法setTimeInMillis(long);可以用它来设置从1970年1月1日算起的一个特定时间。请编程从键盘输入一个长整型的值,然后输出对应的年、月和日。例如输入:1234567898765,输出:2009-1-14
输入 1234567898765 (毫秒数)
输出 2009-1-14 (输出年、月和日,实际应该是2月,因为Java API 从0开始计算月份)
1450921070108
2015-11-24
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long time = input.nextLong();
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(time);
Date ans = gc.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-d");
String s = sdf.format(ans);
String[] strings = s.split("-");
int temp = Integer.parseInt(strings[1]) - 1;
System.out.println(strings[0] + "-" + temp + "-" + strings[2]);
}
}
从下列的抽象类shape类扩展出一个正五边形(regular pentagon)类RPentagon,这个类将正五边形的边长作为私有成员,类中包含初始化这个值的构造方法。 public abstract class shape {// 抽象类 /* 抽象方法 求面积 / public abstract double getArea(); / 抽象方法 求周长 / public abstract double getPerimeter(); } 请编程从键盘输入正五边形的边长值,创建一个正五边形对象,然后输出正五边形的面积和正五边形的周长。计算正五边形的面积公式为: S=5a^2/(4tan(36度))其中a为边长。 或者:S=(1/4)a^2*√(25+10√5) 输出结果保留4位小数。
输入正五边形的边长。例如: 5
输出正五边形的面积和周长。第一行输出面积,第二行输出周长。例如: 43.0119 25
16.8
485.5875
84
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.lang.Math;
//package zt_text_id;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
//BigDecimal b1 = new BigDecimal(a);
Bian b1 = new Bian(a);
DecimalFormat df1 = new DecimalFormat("#.####");
System.out.println(df1.format(b1.getArea()));
System.out.println(df1.format(b1.getPerimeter()));
}
}
abstract class shape{
public abstract double getArea();
public abstract double getPerimeter();
}
class Bian extends shape {
private double a;
public Bian (double a) {
this.a = a;
}
public double getArea() {
double s = a * a/4 * (Math.sqrt(25 + 10 * Math.sqrt(5.0)));
return s;
}
public double getPerimeter() {
return a* 5;
}
}
编写一个类,类中有如下的方法,找出一个在给定字符串的某个字符的出现的次数,方法的声明如下: public static int count(String str, char a) 例如, count(“Welcome”, ‘e’) returns 2. 编写一个测试程序,特使用户输入字符串和一个字符,按照提示输出其出现的次数。 下面是输入和输出的样例,请严格按照输入输出格式进行。
please input the string and the character.
Then output the the number of occurrences of a specified character in the string.
Welcome e
The number of occurrences is 2.
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.lang.Math;
//package zt_text_id;
public class Main {
public static void main(String[] args) {
String a=new String();
int count=0;
Scanner input=new Scanner(System.in);
//System.out.println("");
String string=input.next();
//System.out.println("输入要查找的字符");
String in=input.next();
char[] ch=string.toCharArray();
char c=in.charAt(0);
for (int i = 0; i < ch.length; i++) {
if (c==ch[i]) {
count++;
}
}
System.out.println("The number of occurrences is "+count + ".");
}
}
文件:期中考试成绩.txt中有若干学生的姓名和数学期中考试成绩。 Smith 67 Anderson 75 Lewis 83 Cook 58 David 96 请你编写一个简单的查询成绩程序,当从键盘输入一个姓名时查找到他的数学期中考试分数并按照21%折算后输出。如果没找到则显示Not found. 由于目前的OJ系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的姓名和成绩,当输入的名字为noname时,表示结束。noname后面有一个名字,需要查找其成绩。
Smith 67
Anderson 75
Lewis 83
Cook 58
David 96
noname (表示结束)
Bill
Not found.
Smith 67
Anderson 75
Lewis 83
Cook 58
David 96
noname
Lewis
17.43
import java.util.*;
public class Main{
public static void main(String [] args){
List<Map<String,String>> datas = new ArrayList<Map<String,String>>();
Scanner in = new Scanner(System.in);
String name,grade;
while(true){
name = in.next();
if(name.equals("noname")){
break;
}
grade = in.next();
Map<String,String> map = new HashMap<String,String>();
map.put(name,grade);
datas.add(map);
}
String na = in.next();
for (int i = 0; i < datas.size(); i++) {
if(datas.get(i).containsKey(na)){
System.out.println(Integer.parseInt(datas.get(i).get(na))*0.21);
return;
}
}
System.out.println("Not found.");
}
}
请编写程序,从键盘输入两个整数m,n,找出等于或大于m的前n个素数。
第一个整数为m,第二个整数为n;中间使用空格隔开。例如: 103 3
从小到大输出找到的等于或大于m的n个素数,每个一行。例如: 103 107 109
9223372036854775839 2
9223372036854775907
9223372036854775931
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
String sc = in.next();
BigInteger m = new BigInteger(sc);
int n = in.nextInt();
int i=0;
while(i<n){
if(isPrime(m)){
System.out.println(m);
i++;
}
m=m.add(BigInteger.ONE);
}
}
public static boolean isPrime(BigInteger num) {
return num.isProbablePrime(50);
}
}
求解给定字符串的前缀。
输入数目不定的多对字符串,每行两个,以空格分开。 例如: filename filepath Tom Jack
返回两个字符串的最大前缀,例如: The common prefix is file No common prefix
filename filepath
Tom Jack
The common prefix is file
No common prefix
import java.util.Scanner;
public class Main{
public static int fun(String a, String b){
int k = 0;
int len1 = a.length();
int len2 = b.length();
while(a.charAt(k) == b.charAt(k)){
k++;
}
return k;
}
public static void main(String[] args){
// System.out.println(Main.fun("filename", "filepath"));
Scanner input = new Scanner(System.in);
int num = 0;
int cnt = 0;
String ans = "";
do{
String a = input.nextLine();
if (a.equals("")){
break;
}
String[] strings = a.split(" ");
num = Main.fun(strings[0],strings[1]);
if (num != 0){
ans = a.substring(0,num);
System.out.println("The common prefix is " + ans);
}else{
System.out.println("No common prefix");
}
}while(true);
}
}
创建一个正六边形(regular hexagon)RHexagon类,实现下列接口IShape。RHexagon类将正六边形的边长作为私有成员,类中包含初始化这个值的构造方法。 interface IShape {// 接口 double getArea(); // 求面积 double getPerimeter();// 求周长
} 请编程从键盘输入正六边形的边长值,创建一个正六边形对象,然后输出正六边形的面积和周长。保留4位小数。
正六边形类名:
RHexagon
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
double getArea();
double getPerimeter();
}
//你提交的代码将被嵌入到这里public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
IShape r = new RHexagon (a);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
输入 16.8 (边长) 输出 733.281 (输出的面积) 100.8 (输出的周长)
5
64.9519
30
class RHexagon implements IShape{
private double a;
public RHexagon(double a) {
super();
this.a = a;
}
public double getArea() {
return (3 * Math.sqrt(3)) / 2 * a * a;
}
public double getPerimeter() {
return (a*6);
}
}
创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。 interface IShape {// 接口 public abstract double getArea(); // 抽象方法 求面积 public abstract double getPerimeter(); // 抽象方法 求周长 } ###直角三角形类的定义:
直角三角形类的构造函数原型如下:
RTriangle(double a, double b);
其中 a
和 b
都是直角三角形的两条直角边。
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
public abstract double getArea();
public abstract double getPerimeter();
}
/*你写的代码将嵌入到这里*/public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape r = new RTriangle(a, b);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
3.1 4.2
6.51
12.5202
class RTriangle implements IShape{
private double a;
private double b;
public RTriangle(double a, double b) {
super();
this.a = a;
this.b = b;
}
public double getArea() {
// TODO Auto-generated method stub
return this.a * this.b / 2.0;
}
public double getPerimeter() {
// TODO Auto-generated method stub
return this.a + this.b + Math.sqrt(this.a * this.a + this.b * this.b) ;
}
}
给定两个字符串,求解给定字符串的后缀。按照如下的格式进行输出
输入为一对字符串,以空格分开。 例如:
father mather
返回两个字符串的最大后缀,例如:
The common suffix is ather.
又如:
Tom Jack
No common suffix.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
StringBuilder s1=new StringBuilder(sc.next());
StringBuilder s2=new StringBuilder(sc.next());
StringBuilder s=new StringBuilder();
int len;
if(s1.length()<s2.length())
len=s1.length();
else len=s2.length();
s2=s2.reverse();
s1=s1.reverse();
for(int i=0;i<len;++i)
if (s2.charAt(i)==s1.charAt(i)) {
s.append(s1.charAt(i));
} else break;
if(0 == s.length())
System.out.println("No common suffix.");
else
System.out.println("The common suffix is "+s.reverse()+".");
sc.close();
}
}
如果是数字就输出true , 不是数字就输出false.
3.145
true
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
StringBuffer sb=new StringBuffer(sc.next());
boolean flag=false;
int count = 0;
for(int i=0;i<sb.length()-1;++i){
if(sb.charAt(i)=='.' ){//如果全是 . 怎么搞?
flag=true;
count+=1;
}
else if(Character.isDigit(sb.charAt(i))){
flag=true;
}
else flag=false;
}
if(flag && count==1) System.out.println("true");
else System.out.println("false");
}
}
Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology. The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture. end (表示结束) Institute (第一个字符串,要求用第二个字符串替换) University (第二个字符串)
Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.
The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end
Institute
University
Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String temp;
while (sc.hasNextLine()) {
temp = sc.nextLine();
if (temp.equals("end"))
break;
str = str + '\n' + temp;
}
String str1 = sc.next();
String str2 = sc.next();
String newstr = str.replaceAll(str1, str2);
System.out.println(newstr);
sc.close();
}
}
定义IntegerStack
接口,用于描述一个存放Integer元素的栈的常见方法:
public Integer push(Integer item);
//如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为nullpublic Integer peek(); //获得栈顶元素,如果为空,则返回null.public boolean empty(); //如果为空返回truepublic int size(); //返回栈中元素个数
定义IntegerStack的实现类ArrayIntegerStack
,内部使用数组实现。创建时,可指定内部数组大小。
如果IntegerStack接口的实现类内部使用ArrayList来存储元素,怎么实现?测试代码需要进行什么修改?
5
3
1 2 3
2
1
2
3
3,false,3
[1, 2, 3, null, null]
3
2
1,false,1
[1, 2, 3, null, null]
import com.sun.org.apache.regexp.internal.RE;
import java.util.Arrays;
import java.util.Scanner;
interface IntegerStack{
public Integer push(Integer item);
//如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。
public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null
public Integer peek(); //获得栈顶元素,如果为空,则返回null.
public boolean empty(); //如果为空返回true
public int size(); //返回栈中元素个数
}
class ArrayIntegerStack implements IntegerStack{
private int a[];
private int end=0;
public ArrayIntegerStack(int num) {
a=new int[num];
}
@Override
public Integer push(Integer item) {
if (item==null){
return null;
}
if (end==a.length){
return null;
}
a[end]=item;
end++;
return item;
}
@Override
public Integer pop() {
if (end==0){
return null;
}
end--;
return a[end];
}
@Override
public Integer peek() {
if (end==0){
return null;
}
return a[end-1];
}
@Override
public boolean empty() {
if (end==0){
return true;
}
return false;
}
@Override
public int size() {
return end;
}
@Override
public String toString() {
String s="";
int i=0;
while (i<end-1){
s+=a[i]+", ";
i++;
}
if (end==0){
while (i<a.length-1){
s+="null, ";
i++;
}
s+="null";
}else {
if (end<a.length){
s+=a[i]+", ";
for (int p=0;p<a.length-end-1;p++){
s+="null, ";
}
s+=null;
}else {
s+=a[i];
}
}
return "["+s+"]";
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayIntegerStack arrayIntegerStack = new ArrayIntegerStack(sc.nextInt());
int num=sc.nextInt();
for(int i=0;i<num;i++){
System.out.println(arrayIntegerStack.push(sc.nextInt()));
}
System.out.println(arrayIntegerStack.peek()+","+arrayIntegerStack.empty()+","+arrayIntegerStack.size());
String arr=arrayIntegerStack.toString();
System.out.println(arrayIntegerStack.toString());
int time=sc.nextInt();
for (int i=0;i<time;i++){
System.out.println(arrayIntegerStack.pop());
}
System.out.println(arrayIntegerStack.peek()+","+arrayIntegerStack.empty()+","+arrayIntegerStack.size());
System.out.println(arr);
}
}
给定一个字符串,对该字符串进行排序,请输出排好序的字符串。要求能够连续输入输出的字符串。
在一行输入一个字符串
输出排好序的字符串的序列
fecbad
abcdef
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] chs = str.toCharArray();
sortChar(chs);
String res = String.valueOf(chs);
System.out.println(res);
}
//冒泡排序
public static void sortChar(char[] chs){
for (int i = 0; i < chs.length; i++) {
for (int j = 0; j < chs.length - 1 -i; j++) {
if(chs[j] > chs[j+1]){
char tmp = chs[j];
chs[j] = chs[j+1];
chs[j+1] = tmp;
}
}
}
}
//选择排序算法
public static void xuanZeSort(char[] chs){
for(int i = 0; i < chs.length-1; i++){
for(int j = i+1; j<chs.length; j++){
if(chs[j] < chs[i]){
char temp = chs[j];
chs[j] = chs[i];
chs[i] = temp;
}
}
}
}
}
文件phonebook1.txt中有若干联系人的姓名和电话号码。 高富帅 13312342222 白富美 13412343333 孙悟空 13512345555 唐三藏 13612346666 猪悟能 13712347777 沙悟净 13812348888 请你编写一个简单的通信录程序,当从键盘输入一个姓名时查找到对应的电话号码并输出。如果没找到则显示Not found. 由于目前的自动裁判系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的姓名和电话号码,当输入的名字为noname时,表示结束。noname后面有一个名字,需要查找其对应的电话号码。
高富帅 13312342222 白富美 13412343333 孙悟空 13512345555 唐三藏 13612346666 猪悟能 13712347777 沙悟净 13812348888 noname (表示结束) 唐三藏 (需要查找此人的电话号码)
13612346666 (输出对应的电话号码)
白富美 13412343333
孙悟空 13512345555
唐三藏 13612346666
猪悟能 13712347777
沙悟净 13812348888
noname
白骨精
Not found.
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
HashMap<String, String> telephone = new HashMap<>();
while (true) {
telephone.put(input.next(), input.next());
if(telephone.get("noname")!=null) {
break;
}
}
String man =telephone.get("noname");
if(telephone.get(man)!=null) {
System.out.println(telephone.get(man));
}
else {
System.out.println("Not found.");
}
input.close();
}
}
(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as a double type. Write the following method that returns the location of the largest element in a two-dimensional array: public static Location locateLargest(double[][] a) The return value is an instance of Location.Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array.
Enter the row and column and the number in the array. For example: 2 3 234 223 444 111 343 454
displays the location of the largest element in the array. Such as : e location of the largest element is 454.0 at (1, 2)
2 3
234 223 444
111 343 454
The location of the largest element is 454.0 at (1, 2)
import java.util.*;
class Location{
public int row = 0;
public int column = 0;
public double maxValue = 0;
Location(){}
}
public class Main {
public static Location locateLargest(double [] [] a) {
Location b = new Location();
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
{
if(b.maxValue<a[i][j])
{
b.maxValue = a[i][j];
b.row = i;
b.column = j;
}
}
return b;
}
public static void main(String[] args) {
Location q = new Location();
Scanner in = new Scanner(System.in);
int w = in.nextInt();
int e = in.nextInt();
double[][] a = new double[w][e];
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
{
a[i][j] = in.nextDouble();
}
q = locateLargest(a);
//System.out.printf("The location of the largest element is %.1f at (%d, %d)\n",q.maxValue,q.row,q.column);
System.out.println("The location of the largest element is "+q.maxValue+" at ("+q.row+", "+q.column+")");
in.close();
}
}
(Largest rows and columns) Write a program that input fills in 0s and 1s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1s. (Hint: Use two ArrayLists to store the row and column indices with the most 1s.) Here is a sample run of the program: Enter the array size n: 4 The random array is 0 0 1 1 0 0 1 1 1 1 0 1 1 0 1 0 The largest row index: 2 The largest column index: 2, 3
Enter the array size n and the n x n numbers that input 0s and 1s . The first line input the length n of the matrix . And input the value of the matrix the other n line.
Displays the rows and columns with the most 1s…
4
0 0 1 1
0 0 1 1
1 1 0 1
1 0 1 0
Highest row: [2]
Highest column: [2, 3]
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] a = new int[n][n];
int[] row = new int[n];
int[] column = new int[n];
int max_row = 0;
int max_column = 0;
// for (int i=0;i
// row[i] = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = in.nextInt();
if (a[i][j] == 1)
row[i]++;
}
if (row[i] > max_row)
max_row = row[i];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[j][i] == 1)
column[i]++;
}
if (column[i] > max_column)
max_column = column[i];
}
int b = 0;
System.out.print("Highest row: [");
for(int i=0;i<n;i++)
{
if(row[i]==max_row)
{
if((++b) == 1)
System.out.print(i);
else System.out.print(" ,"+i);
}
}
b = 0;
System.out.println("]");
System.out.print("Highest column: [");
for(int i=0;i<n;i++)
{
if(column[i]==max_column)
if((++b) == 1)
System.out.print(i);
else System.out.print(", "+i);
}
System.out.println("]");
}
}
编程从键盘输入一个整数,计算出阶乘并输出。
输入 39
输出:20397882081197443358640281739902897356800000000
58
2350561331282878571829474910515074683828862318181142924420699914240000000000000
import java.util.Scanner;
import java.math.BigInteger;
public class Main
{
public static BigInteger compute(BigInteger number)
{
BigInteger result=new BigInteger("1");
BigInteger one=new BigInteger("1");
for(BigInteger i=number; i.intValue()>0; i=i.subtract(one))
result = result.multiply(i);
return result;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
BigInteger val=input.nextBigInteger();
System.out.println(compute(val));
input.close();
}
}
在一大堆数据中找出重复的是一件经常要做的事情。现在,我们要处理许多整数,在这些整数中,可能存在重复的数据。
你要写一个程序来做这件事情,读入数据,检查是否有重复的数据。如果有,输出“YES”这三个字母;如果没有,则输出“NO”。
你的程序首先会读到一个正整数n,1<=n<=100000。然后是n个整数。
如果这些整数中存在重复的,就输出:
YES
否则,就输出:
NO
5
1 2 3 1 4
YES
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
cin.nextLine();
String str = cin.nextLine();
cin.close();
String [] s = str.split(" ");
Set<String> st = new HashSet<String>();
for(int i = 0; i < s.length; ++ i) {
st.add(s[i]);
if( st.size() != i + 1) {
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
}
编写程序,实现字符串大小写的转换并倒序输出。
输入一行字符串
字符串大小写的转换,并倒序输出
Hello World!
!DLROw OLLEh
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
String s=input.nextLine();
char[] ch=s.toCharArray();
StringBuffer str=new StringBuffer();
for(int i=ch.length-1;i>=0;i--) {
if(ch[i]>='a'&&ch[i]<='z') {
str.append(String.valueOf(ch[i]).toUpperCase());
}
else if(ch[i]>='A'&&ch[i]<='Z') {
str.append(String.valueOf(ch[i]).toLowerCase());
}
else if(ch[i]==' ') {
str.append(String.valueOf(ch[i]));
}
else {
str.append(String.valueOf(ch[i]));
}
}
System.out.println(str.toString());
}
}
(Combine two lists then sorted it.)
Write a method that returns the union of two array lists of integers using the following header:
public static ArrayList union( ArrayList list1, ArrayList list2)
For example, the union of two array lists {2,3,1,5} and {3,4,6} is {2, 3, 1, 5, 3, 4, 6}.
Write a test program that prompts the user to enter two lists, then sorted the union list, finally displays their sorted union. The numbers are separated by exactly one space in the output.
Write a test program that prompts the user to enter the two number m,n for the length of two arrays in the first line, and the next two line input m integer and n intergers for the two array. After sort theunion intergers and displays the sorted union list separated by exactly one space.
Input the two number m,n for the length of two arrays in the first line, and the next two line input m integer and n intergers .
Displays the sorted union list separated by exactly one space…
3 4
23 44 32
12 43 32 44
12 23 32 32 43 44 44
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt()+input.nextInt();
int[] num=new int[n];
for(int i=0;i<n;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
for(int i=0;i<n;i++) {
System.out.print(num[i]+" ");
}
input.close();
}
}
(Geometry: intersecting point) Suppose two line segments intersect. The two end-points for the first line segment are (x1, y1) and (x2, y2) and for the second line segment are (x3, y3) and (x4, y4).Write a program that prompts the user to enter these four endpoints and displays the intersecting point. the intersecting point can be found by solving a linear equation. Write the LinearEquation class in Programming to solve this equation. You need to keep the last three decimal places. (你需要保留小数点后三位)
Enter eight double number
Displays the intersecting point or The two lines are parallel .
2.3 4.5 6.7 -3.4 4 5.6 6.7 9.1
The intersecting point is at (2.657,3.859)
1 2 3 4 5 6 7 8
The two lines are parallel
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
double x1,x2,x3,x4,y1,y2,y3,y4;
double a,b,c,d,e,f,x,y,t;
DecimalFormat num = new DecimalFormat("#.000");
Scanner input = new Scanner(System.in);
x1=input.nextDouble();
y1=input.nextDouble();
x2=input.nextDouble();
y2=input.nextDouble();
x3=input.nextDouble();
y3=input.nextDouble();
x4=input.nextDouble();
y4=input.nextDouble();
a=y1-y2;
b=x2-x1;
c=y3-y4;
d=x4-x3;
e=a*x1+b*y1;
f=c*x3+d*y3;
t=a*d-b*c;
if(t!=0) {
x=(e*d-b*f)/t;
y=(a*f-e*c)/t;
System.out.println("The intersecting point is at ("+num.format(x)+","+num.format(y)+")");
}
else {
System.out.println("The two lines are parallel");
}
input.close();
}
}