Java上机题汇总

2021.3.3

知识

读入/输出

  • 输出:System.out.println(“Hello, Java!”);
  • 读入:
    Scanner s = new Scanner(System.in);
    s.hasNextLine()
    String line = s.nextLine();
    b=i.nextInt();
    String s=in.next();
    s.close();

HELLO JAVA

Output a greeting phrase "Hello, Java! "
Input: None
Output: Hello, Java!
Hints:
Please output things according to the requirements. No extra output is allowed.

The class name MUST be Main. It’s case sensitive.

public class Main{
   public static void main(String[] args) {
	   System.out.println("Hello, Java!");
   }
}

console input/output

You are requested to output what you got from the system console.
Input: A line of string, until no inut is found! Example:
This is the first line.
This is the second line.

This is the end.
Output: What you get from the console(keyboard)
This is the first line.
This is the second line.

This is the end.
Hints:
On getting input from the console, you can refer to various articles on the web. For reading a line from the console, here is a example:
Scanner s = new Scanner(System.in);
if (s.hasNextLine()) {
String line = s.nextLine();

}

import java.util.*;
public class Main {
  public static void main(String[] args) {
	  Scanner s = new Scanner(System.in);
	  while(s.hasNextLine()) {
	  String line = s.nextLine();
	  System.out.println(line);
	  }
  }
}

A+B问题

1

You are requested to calculate the sum of two integral numbers a and b.
Input:
A pair of number seperated by the blank character. Example:
5 12
Output: the sum of the input pair
17
Hints:
On geting input from the console, you can refer to various articles on the web. Here is a example:
Scanner s = new Scanner(System.in);
int age = s.nextInt();
If you want to get the whole line, you can use:
String str = s.nextLine();

import java.util.*;
public class Main {
  public static void main(String[] args) {
	  Scanner i = new Scanner(System.in);
	  int a=i.nextInt();
	  int b=i.nextInt();
	  System.out.println(a+b);
  }
}

2

You are requested to calculate the sum of two integers a and b. This time we go further. There are multiple pair of a and b in a testing group. So you need to calculate the sum several times for each testing group. Note that there may be huge number of pairs to calculate. So don’t make an assumption of how many test cases.
Input:
Test case count T following by each test case. Example:
3
5 12
1 1
3 -5
Output: the sum of each input pair
17
2
-2

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  ArrayList al = new ArrayList();
	  int i=in.nextInt();
	  for(int j=0;j<i;j++){
	  int a=in.nextInt();
	  int b=in.nextInt();
	  al.add(a+b);
	  }
	  for(int j=0;j<i;j++)System.out.println(al.get(j));
  }
}

3

Description
Your task is to Calculate a + b.
Too easy?! Of course! I specially designed the problem for acm beginners.
You must have found that some problems have the same titles with this one, yes, all these problems were designed for the same aim.
Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
Output
For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.
Sample Input
1 5
10 20
Sample Output
6
30

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  ArrayList al = new ArrayList();
	  int i=0;
	  int a=in.nextInt();
	  int b=in.nextInt();
	  al.add(a+b);
	  i++;
	  if(in.hasNextLine()){
	  a=in.nextInt();
	  b=in.nextInt();
	  al.add(a+b);
	  i++;
	  }
	  for(int j=0;j<i;j++)System.out.println(al.get(j));
  }
}

Approximate PI

PI can be computed using the following formula:
PI = 4 * (1-1/3+1/5-1/7+1/9-…+1/n).
For a given n, write a program that displays the result of PI
Input:
A single line containing a odd number n. Example:
9
Output: the result of calculated PI, keep 6 digit after the decimal point.
3.339683

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  int n=in.nextInt();
	  double sum=0,temp=0;
	  int k=1;
	  for(int j=1;j<=n;j=j+2) {		  
		  temp=1.0/(double)j;
		  temp=temp*k;
		  sum+=temp;
		  k=-1*k;
	  }
      double PI=4*sum;
      System.out.printf("%.6f\n",PI);
  }
}

Repeat

Repeat 1

Given a non negative number n and a string s, you are expected to repeatedly output the string s n times.
Input:
4
aabb
output:
aabbaabbaabbaabb

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  int n=in.nextInt();
	  String s=in.next();
	  for(int i=0;i<n-1;i++)
		  System.out.printf(s+" ");
	  System.out.println(s);
  }
}

Repeat 2

Given a non negative number n and a string s, you are expected to repeatedly output the string s in n lines.
Input:
4
aabb
output:
aabb
aabb
aabb
aabb

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  int n=in.nextInt();
	  String s=in.nextLine();
	  if(in.hasNextLine()){
	  s=in.nextLine();
	  }
	  for(int j=0;j<n;j++)System.out.println(s);
  }
}

2021.3.17

知识

integer转string

String t=Integer.toString(m);

string转数组

String num = s.next();
char[] arr = num.toCharArray();

string取空格

String c=m.replaceAll(" ", “”);

public类

class Vehicle{
double load;
double maxLoad;
public double getLoad()
{
	return load;
}
public double getMaxLoad()
{
	return maxLoad;
}
public Vehicle(double maxload)
{
	maxLoad=maxload;
}
}

private 类

class Vehicle{
private double load;
private double maxLoad;
public double getLoad()
{
	return load;
}
public double getMaxLoad()
{
	return maxLoad;
}
public Vehicle(double maxload)
{
	maxLoad=maxload;
}
public boolean addBox(double weight)
{
	if (load+weight>getMaxLoad())return false;
	else 
		{
		load+=weight;
		return true;
		}
}
}

Digit Count

Given a number n, you are required to output how many digits are there.
There are several test cases for each test group.
Input: Test case count T following by each test case. Example:
2
12
120
Output:
2
3

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
	  int[] l=new int[100];
	  Scanner in = new Scanner(System.in);
	  int n=in.nextInt();
	  for(int j=0;j<n;j++) {
		int m=in.nextInt();
		String t=Integer.toString(m);
		l[j]=t.length();
	  }
	  for(int j=0;j<n;j++) {
			System.out.println(l[j]);
		  }
  }
}

Unique Digits

Given a number n, you are required to output its unique digits in appearing order. There are several test cases for each test group.
Input: Test case count T following by each test case, preceding zeros may exist. Example:
5
1212
120
0121
0000
-23
Output:
12
120
012
0
23

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int number = s.nextInt();
for(int i = 0; i < number; i++)
{
String num = s.next();
char[] arr = num.toCharArray();
int j = 0;
if(arr[0]=='-') j = 1;
outer:for(; j<arr.length; j++)
{
for(int m = 0;m<j;m++)
if(arr[m]==arr[j])
continue outer;
System.out.print(arr[j]);
}
System.out.print("\n");
}
s.close();
}
}

Sum of digits

Given a number n, you are required to output the sum of its digits. There are several test cases for each test group.
Input: Test case count T following by each test case. Example:
5
1211
1234
012
1111
-23

Output:
5
10
3
4
5

import java.util.*;  
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
   int[] sum=new int[10];
   for(int i=0;i<10;i++)sum[i]=0;
   Scanner in = new Scanner(System.in);
   int n=in.nextInt();
   for(int j=0;j<n;j++) {
  int m=in.nextInt();
  int num=m;
  String t=Integer.toString(m);
  int l=t.length();
  if(num>=0)
  {
   char[]strarray=t.toCharArray();
   for(int i=0;i<l;i++)
   {
    sum[j]=strarray[i]-'0'+sum[j];
  } 
  }
  else {
  char[]strarray=t.toCharArray();
  for(int i=1;i<l;i++)
  {
   sum[j]=strarray[i]-'0'+sum[j];
 }
  }
   }
   for(int j=0;j<n;j++) {
   System.out.println(sum[j]);
    }
  }
}

foo bar ba

You are given two numbers “from”(inclusive) and “to”(inclusive). And you are expected to create an application that loops from “from” to “to” and prints out each value on a separate line, except print out “foo” for every multiple of 3, “bar” for every multiple of 5, and “baz” for every multiple of 7.
If “From” is greater than “to”, then output a blank line.
For example: if from=1 and to=16, then it will give the following output:
1
2
3 foo
4
5 bar
6 foo
7 baz
8
9 foo
10 bar
11
12 foo
13
14 baz
15 foo bar
16

Input: Total test case count T following by T cases of test instances. Example:
3
4 5
6 10
3 -1
output:
4
5 bar
6 foo
7 baz
8
9 foo
10 bar

import java.util.*;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
   int[] sum=new int[10];
      for(int i=0;i<10;i++)sum[i]=0;
   Scanner in = new Scanner(System.in);
   int n=in.nextInt();
   for(int j=0;j<n;j++) {
  int p=in.nextInt();
     int q=in.nextInt();
  if(p>q)
	  {
	  if(p!=3)System.out.println();
	  else continue;
	  }
  else{
   for(int t=p;t<=q;t++)
   {
    if(t%5==0&&t%3!=0&&t%7!=0)System.out.println(t+" bar");
    else if(t%3==0&&t%5!=0&&t%7!=0)System.out.println(t+" foo");
    else if(t%7==0&&t%5!=0&&t%3!=0)System.out.println(t+" baz");
    else if(t%7==0&&t%5!=0&&t%3==0)System.out.println(t+" foo baz");
    else if(t%7==0&&t%5==0&&t%3!=0)System.out.println(t+" bar baz");
    else if(t%7!=0&&t%5==0&&t%3==0)System.out.println(t+"foo bar");
    else if(t%7==0&&t%5==0&&t%3!=0)System.out.println(t+"foo bar baz baz");
    else System.out.println(t);
   } 
  }
  }
}
}

Reverse it

Given a number n, you are required to output its reverse counterpart. that is, the most significant digit become the list significant digit and so on. There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
5
12000
11111
012
5
-23

Output:
21
11111
21
5
-32

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int times = s.nextInt();
for(int i = 0; i < times; i++)
{
int number = s.nextInt();
if(number < 0)
{
number = Math.abs(number);
System.out.print("-");
}
while(number%10 == 0) number /= 10;
while(number>=1)
{
System.out.print(number%10);
number /= 10;
}
System.out.print("\n");
}
s.close();
}
}

count number

Give you a character array, you are required to Count the number of occurrences of each character and print it to the console.

Input: a character array.
Output: the number of occurrences of each character .
Example:
a f m f o b b s n

a–1
b–2
f–2
m–1
n–1
o–1
s–1

import java.util.*;
import java.util.ArrayList;
public class Main{
  public static void main(String[] args) {
	  Scanner in = new Scanner(System.in);
	  int count[]=new int[26];
	  for(int j=0;j<26;j++)count[j]=0;
	  String m=in.nextLine();
	  String c=m.replaceAll(" ", "");
	  int l=c.length();
	 char[] strarray=c.toCharArray();
	 for(int i=0;i<l;i++)
	 {
		 int t=strarray[i]-'a';
		 count[t]++;
	 }
	 for(int i=0;i<26;i++)
	 {
		 int t=i+97;
		 char s=(char)t;
		 if(count[i]!=0)System.out.println(s+"--"+count[i]);
	 }
  }
  }

No Information Hiding

In this version of the Vehicle class, you will leave the attributes public so that the test program TestVehicle1 will have direct access to them.
1,Create a class Vehicle that implements the above UML diagram.
Include two public attributes: load “the current weight of the vehicle’s cargo” and maxLoad “the vehicle’s maximum cargo weight limit”.
Include one public constructor to set the maxLoad attribute.
Include two public access methods: getLoad to retrieve the load attribute and getMaxLoad to retrieve the maxLoad attribute.
Note that all of the data are assumed to be in kilograms.
2,The test program Main.java is preset. So just submit your Vehicle class. If everything is ok, The output will be as expected. You can read the test program. Notice that the program gets into trouble when the last box is added to the vehicle’s load because the code does not check if adding this box will exceed the maxLoad.
3,You can get the test code and run the Main class locally. The output generated should be:
Creating a vehicle with a 10,000kg maximum load. Add box #1 (500kg) Add box #2 (250kg) Add box #3 (5000kg) Add box #4 (4000kg) Add box #5 (300kg) Vehicle load is 10050.0 kg
Note: The test Main class is ready as is shown. you can add it to your code.
Preset Code
Prepend Code
/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW /
public class Main {
public static void main(String[] args) {
// Create a vehicle that can handle 10,000 kilograms weight
System.out.println(“Creating a vehicle with a 10,000kg maximum load.”);
Vehicle vehicle = new Vehicle(10000.0);
// Add a few boxes
System.out.println(“Add box #1 (500kg)”);
vehicle.load = vehicle.load + 500.0;
System.out.println(“Add box #2 (250kg)”);
vehicle.load = vehicle.load + 250.0;
System.out.println(“Add box #3 (5000kg)”);
vehicle.load = vehicle.load + 5000.0;
System.out.println(“Add box #4 (4000kg)”);
vehicle.load = vehicle.load + 4000.0;
System.out.println(“Add box #5 (300kg)”);
vehicle.load = vehicle.load + 300.0;
// Print out the final vehicle load
System.out.println(“Vehicle load is " + vehicle.getLoad() + " kg”);
}
}
/
PRESET CODE END - NEVER TOUCH CODE ABOVE */

import java.util.*;
import java.util.ArrayList;
class Vehicle{
double load;
double maxLoad;
public double getLoad()
{
	return load;
}
public double getMaxLoad()
{
	return maxLoad;
}
public Vehicle(double maxload)
{
	maxLoad=maxload;
}
}
public class Main {
  public static void main(String[] args) {
	  System.out.println("Creating a vehicle with a 10,000kg maximum load.");
	  Vehicle vehicle = new Vehicle(10000.0);
	  // Add a few boxes
	  System.out.println("Add box #1 (500kg)");
	  vehicle.load = vehicle.load + 500.0;
	  System.out.println("Add box #2 (250kg)");
	  vehicle.load = vehicle.load + 250.0;
	  System.out.println("Add box #3 (5000kg)");
	  vehicle.load = vehicle.load + 5000.0;
	  System.out.println("Add box #4 (4000kg)");
	  vehicle.load = vehicle.load + 4000.0;
	  System.out.println("Add box #5 (300kg)");
	  vehicle.load = vehicle.load + 300.0;
	  // Print out the final vehicle load
	  System.out.println("Vehicle load is " + vehicle.getLoad() + " kg");
  
  }
  }

Basic Information Hiding

To solve the problem from the first version, you will hide the internal classdata (load and maxLoad) and provide a method, addBox, to perform the proper checking that the vehicle is not being overloaded.
1,
Create a class Vehicle that implements the above UML diagram.
You may wish to copy the Vehicle.java file you created in version #1.
Modify the load and maxLoad attributes to be private.
Add the addBox method. This method takes a single argument, which is the weight of the box in kilograms. The method must verify that adding the box will not violate the maximum load. If a violation occurs the box is rejected by returning the value of false; otherwise the weight of the box is added to the vehicle load and the method returns true.
Hint: you will need to use an “if” statement. Here is the basic form of the conditional form:
if ( ) { * } else { * }
Note that all of the data are assumed to be in kilograms.
2,
Read the Main.java code. Notice that the code can not modify the load attribute directly, but now must use the addBox method. This method returns a true or false value which is printed to the screen.
3,
Compile the Vehicle and Main classes locally.
4,
Run the Main class. The output generated should be something like these:
Creating a vehicle with a 10,000kg maximum load. Add box #1 (500kg) : true Add box #2 (250kg) : true Add box #3 (5000kg) : true Add box #4 (4000kg) : true Add box #5 (300kg) : false Vehicle load is 9750.0 kg
Note:The test Main class is ready as is shown. you can add it to your code.
Preset Code
Prepend Code
/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW /
public class Main { public static void main(String[] args) {
// Create a vehicle that can handle 10,000 kilograms weight
System.out.println(“Creating a vehicle with a 10,000kg maximum load.”);
Vehicle vehicle = new Vehicle(10000.0);
// Add a few boxes
System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500.0));
System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250.0));
System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000.0));
System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000.0));
System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300.0));
System.out.println("Add box #5 (250kg) : " + vehicle.addBox(250.0));
// Print out the final vehicle load
System.out.println(“Vehicle load is " + vehicle.getLoad() + " kg”);
} }
/
PRESET CODE END - NEVER TOUCH CODE ABOVE */

import java.util.*;
import java.util.ArrayList;
class Vehicle{
private double load;
private double maxLoad;
public double getLoad()
{
	return load;
}
public double getMaxLoad()
{
	return maxLoad;
}
public Vehicle(double maxload)
{
	maxLoad=maxload;
}
public boolean addBox(double weight)
{
	if (load+weight>getMaxLoad())return false;
	else 
		{
		load+=weight;
		return true;
		}
}
}
public class Main {
  public static void main(String[] args) {
	  System.out.println("Creating a vehicle with a 10,000kg maximum load.");
	  Vehicle vehicle = new Vehicle(10000.0);
	  // Add a few boxes
	  System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500.0));
	  System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250.0));
	  System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000.0));
	  System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000.0));
	  System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300.0));
	  System.out.println("Add box #5 (250kg) : " + vehicle.addBox(250.0));
	  // Print out the final vehicle load
	  System.out.println("Vehicle load is " + vehicle.getLoad() + " kg");
  
  }
  }

2021.4.1

知识

结构体相关知识

Create a Simple Banking Package

Objective

This exercise will introduce you to the banking project which we will return to in several labs later. This project will (eventually) consist of a bank with several customers with several account each and a report. These classes will evolve over the next several modules.

In this exercise, you will create very simple version of the Account class. You will place this source file in the banking package. A test program, Main, has been written in the default package that creates a single account. It initializes the balance of that account and performs several simple transactions. Finally, the test program displays the final balance of the account.

p1

Directions

Note: the directions applies for your local operations. When submit your code, you MUST comment out the package statement in your source code so that the class you designed is in the default package because our online judge system do not support packages. That is, all the source code are in the same package(folder). Therefore, the testing Main class should also be modifid locally(just comment out the import banking statements.) The test Main class is ready as is shown. you can add it to your code.

1,
Create the banking directory. Use a command such as:
mkdir banking
under the command line prompt.

2,
Create the Account class in the file Account.java under the banking directory. This class must implement the model in the above UML diagram.
declare one private object attribute: balance; this attribute will hold the current (or “running”) balance of the bank account
declare a public constructor that takes one parameter (init_balance); that populates the balance attribute
declare a public method getBalance that retrieves the current balance
declare a public method deposit that adds the amount parameter to the current balance
declare a public method withdraw that removes the amount parameter from the current balance

3,
In the main test directory(where the Main class lives), compile the Main.java file. This has a cascading effect of compiling all of the classes used in the program; thus compiling the Customer.java and Account.java files under the banking directory.
javac -d . Main.java

4,
Run the Main class. You shoud see the following output:
Creating an account with a 500.00 balance. Withdraw 150.00 Deposit 22.50 Withdraw 47.62 The account has a balance of 324.88

Preset Code
Prepend Code

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */

/* * This class creates the program to test the banking classes. * It creates a new Bank, sets the Customer (with an initial balance), * and performs a series of transactions with the Account object. */

// Note that this import statement is commented // import banking.*;

public class Main{

public static void main(String[] args) { Account account;

// Create an account that can has a 500.00 balance.
System.out.println(“Creating an account with a 500.00 balance.”);
account = new Account(500.00);

System.out.println(“Withdraw 150.00”);
account.withdraw(150.00);

System.out.println(“Deposit 22.50”);
account.deposit(22.50);

System.out.println(“Withdraw 47.62”);
account.withdraw(47.62);

// Print out the final account balance
System.out.println("The account has a balance of " + account.getBalance());

} }

/* PRESET CODE END - NEVER TOUCH CODE ABOVE */

package x;
import java.util.*;
import java.util.ArrayList;
class Account{
	private double balance;//存储余额
	public Account(double blc) {
		balance=blc;
	}
	public double getBalance()
	{
		return balance;
	}
	public void deposit(double amt)
	{
		balance+=amt;
	}
	public void withdraw(double amt)
	{
		balance-=amt;
	}
}
public class x{
  public static void main(String[] args) {
	  System.out.println("Creating an account with a 500.00 balance.");
	  Account account = new Account(500.00);
	  System.out.println("Withdraw 150.00");
	  account.withdraw(150.00);

	  System.out.println("Deposit 22.50");
	  account.deposit(22.50);

	  System.out.println("Withdraw 47.62");
	  account.withdraw(47.62);

	  // Print out the final account balance
	  System.out.println("The account has a balance of " + account.getBalance());
	  
  }
  }

Change Internal Representation of Weight to Newtons

Now suppose that you were going to write some calculations that determine the wear on the vehicle’s engine and frame. These calculations are easier if the weight of the load is measured in newtons.

1, Create a class Vehicle that implements the above UML diagram.

You may wish to copy the Vehicle.java file you created in version #2.
Modify the constructor, getLoad, getMaxLoad, and addBox methods to use a conversion from kilograms (the parameter weight measurement) to newtons (the instance variable measurement). You might want to use the following private methods:

private double kiloToNewts(double weight) { return (weight * 9.8); } private double newtsToKilo(double weight) { return (weight / 9.8); }

Note that now the internal data of the vehicle objects is in newtons and the external data (passed between methods) is still in kilograms.

2, Read the preset Main.java code. Notice that it is identical to the test code in version #2. 3, Compile the Vehicle and Main classes locally. 4, Run the Main class. The output generated should be:

Creating a vehicle with a 10,000kg maximum load. Add box #1 (500kg) : true Add box #2 (250kg) : true Add box #3 (5000kg) : true Add box #4 (4000kg) : true Add box #5 (300kg) : false Vehicle load is 9750.0 kg
You should see no change in the output of the program. This demonstrates that the (private) internal changes to the version #3 Vehicle class did not change the code of the client class Main.

Note:The test Main class is ready as is shown. you can add it to your code.

Preset Code

Prepend Code

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */

public class Main { public static void main(String[] args) {

// Create a vehicle that can handle 10,000 kilograms weight
System.out.println(“Creating a vehicle with a 10,020kg maximum load.”);
Vehicle vehicle = new Vehicle(10020.0);

// Add a few boxes
System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500.0));
System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250.0));
System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000.0));
System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000.0));
System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300.0));
System.out.println("Add box #5 (270kg) : " + vehicle.addBox(270.0));

// Print out the final vehicle load
System.out.println(“Vehicle load is " + vehicle.getLoad() + " kg”);

} }

/* PRESET CODE END - NEVER TOUCH CODE ABOVE */

package x;
import java.util.*;
import java.util.ArrayList;
class Vehicle{
	private double load;
	private double max_load;
	public Vehicle(double mld) {
		max_load=mld;
	}
	private double kiloToNewts(double weight) { 
		return (weight * 9.8);
		}
	private double newtsToKilo(double weight)
	{
		return (weight/9.8);
	}
	public double getLoad()
	{
		return load;
	}
	public double getMaxLoad()
	{
		return max_load;
	}
	public boolean addBox(double weight)
	{
		if(load+weight>max_load)return false;
		else 
			{
			load+=weight;
			return true;
			}
	}
}
public class x{
  public static void main(String[] args) {
	  System.out.println("Creating a vehicle with a 10,020kg maximum load.");
	  Vehicle vehicle = new Vehicle(10020.0);

	  // Add a few boxes
	  System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500.0));
	  System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250.0));
	  System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000.0));
	  System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000.0));
	  System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300.0));
	  System.out.println("Add box #5 (270kg) : " + vehicle.addBox(270.0));

	  // Print out the final vehicle load
	  System.out.println("Vehicle load is " + vehicle.getLoad() + " kg");
  
  }
  }

Binary form

You are required to present a given integer its binary form. There may be several test cases for each test group.

Input: Test case count T following by each test case. Example:
4
12
-1
0
2147483647

Output:
1100
11111111111111111111111111111111
0
1111111111111111111111111111111

package x;
import java.util.*;
public class x{
  public static void main(String[] args) {
	  Scanner in=new Scanner(System.in);
	  int num=in.nextInt();
	  for(int i=0;i<num;i++)
	  { int n;
		int[] binary=new int[32]; 
		int decimal=in.nextInt();
		if(decimal<0)
		{	
			decimal=2147483647+decimal+1;
			//decimal=4294967296+decimal;
			n=0;
			while(decimal>0)
	    {
	       binary[n]=decimal%2;
	       n++;
	       decimal=decimal/2;
	    }	
			System.out.print("1");
			for(int j=n-1;j>=0;j--)
				System.out.print(binary[j]);
			System.out.println();
		}
		else if(decimal>0)
		{
			n=0;
			while(decimal!=0)
	    {
	       binary[n]=decimal%2;
	       n++;
	       decimal=decimal/2;
	    }	
			for(int j=n-1;j>=0;j--)
				System.out.print(binary[j]);
			System.out.println();
	  }
		else 
           {	
			System.out.println("0");
           }
	 }
  }
  }

The UFOs

Problem Description

It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group’s turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.

Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where “A” is 1 and “Z” is 26. For instance, the group “USACO” would be 21 * 19 * 1 * 3 * 15 = 17955. If the group’s number mod 47 is the same as the comet’s number mod 47, then you need to tell the group to get ready! (Remember that “a mod b” is the remainder left over after dividing a by b; 34 mod 10 is 4.)

Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing “GO” if they match and “STAY” if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.

Examples:

Input Output

COMETQ
HVNGAT

GO

ABSTAR
USACO

STAY
package x;
import java.util.*;
public class x{
  public static void main(String[] args){
	  Scanner in=new Scanner(System.in);
	  while(in.hasNext()) {
	  String comet=in.next();
	  String group=in.next();
	  int comet_num=1;
	  int group_num=1;
	  int comet_len=comet.length();
	  int group_len=group.length();
	  char[] comet_arr = comet.toCharArray();
	  char[] group_arr = group.toCharArray();
	  int number;
	  for(int i=0;i<comet_len;i++)
	  {
		  number=comet_arr[i]-'A'+1;
		  comet_num=comet_num*number;
	  }
	  for(int i=0;i<group_len;i++)
	  {
		  number=group_arr[i]-'A'+1;
		  group_num=group_num*number;
	  }
	  if(comet_num%47==group_num%47)System.out.println("Go");
	  else System.out.println("stay");
	  }
  }
  }

Value Added Tax

In Russia, the Value Added Tax is 18% for almost all goods, with the exception of certain food items, which have a Value Added Tax of only 10%.

You are given a String of product , the name of a product, and an int price , the price of the product before tax. You are also given a list of food , each element of which is the name of a food product. If the given product is an element in food, it is a food item (and thus subject to 10% tax), and otherwise, it is a non-food item (and thus subject to 18% tax). Calculate the price of the product after tax has been added.

Constraints:
product will contain between 1 and 50 characters, inclusive.
Each character in product will be a lowercase letter (‘a’-‘z’).
price will be between 1 and 1000, inclusive.
food list will contain between 1 and 50 elements, inclusive.
Each element of food will contain between 1 and 50 characters, inclusive.
Each character in each element of food will be a lowercase letter (‘a’-‘z’).
All elements of food will be distinct.
Input

The first line contains a single integer T tells that there are T case in the problem. Then there are 2 lines for each test case. The first line is the product name and its price. And the second line is a food list with the first integer indicating the number of food product in the list, following the food product names.
Output

The price of the product after tax has been added. Reserve 2 digit after the point.
Sample Input

3
milk 1
3 bread butter milk
car 100
3 bread butter milk
abc 57
3 a b c
Sample Output

1.10
118.00
67.26

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	  Scanner in=new Scanner(System.in);
	  int number=in.nextInt();
	  DecimalFormat df=new DecimalFormat(".00");
	  String[] str=new String[10];
	  for(int i=0;i<number;i++)
	  {
		  String item=in.next();
		  int price=in.nextInt();
          int num=in.nextInt();
          for(int j=0;j<num;j++)
               str[j]=in.next();
          int flag=0;
          for(int j=0;j<num;j++)
          {
        	  if(item.equals(str[j]))flag=1;
          }
          if(flag==1)
        	  {float p;
        	  p=(float)(price*1.10);
        	  System.out.println(df.format(p));
        	  }
          else {
        	  float p;
        	  p=(float)(price*1.18);
        	  System.out.println(df.format(p));
          }
	  }
  }
  }

prime factors

Problem: Decompose a positive integer into prime factors.
For example:
Input: 90
Output:233*5

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	  Scanner in=new Scanner(System.in);
	  int number=in.nextInt();
	  int k=0;
	  int[] num=new int[20];
	  for(int i=2;i<=number;i++)
	  {  
		  if(number%i==0)
		  {
			  int flag=0;
			  for(int j=2;j<i;j++)
			  {
				  if(i%j==0) {
					  flag=1;
					  break;
				  }
			  }
			  if(flag==0)
			  {
				  num[k]=i;
				  k++;
				  //System.out.println(i);
				  number=number/i;
				  i=1;
			  }
		  }
	  }
	  int m;
	 for(m=0;m<k-1;m++)System.out.print(num[m]+"*");
	 System.out.println(num[m]);
  }
  }


Circle count

There are n people in a circle, arranged in order. Start counting from the first person (from 1 to 3). Anyone who reports to 3 will withdraw from the circle and ask which number is the original one left?

For example:
1.
Input: 3
Output: 2
2.
Input: 4
output: 1

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	  Scanner in=new Scanner(System.in);
	  int number=in.nextInt();
	  int n=number;
	  int[] arr=new int [number];
	  System.out.println(number);
	  int i;
	  for(i=0;i<number;i++)
		  arr[i]=1;
	  int temp=0;
	  i=0;
	  while(n>1)
	  {
		  if(arr[i]!=0)
		  {
			  temp++;
			  if(temp==3)
			  {
			  arr[i]=0;
			  n--;
			  temp=0;
			  }
			  
		  }
		  i=(i+1)%number;
	  }
	  for(i=0;i<number;i++)
	  {
		  if(arr[i]!=0)
		  System.out.println(i+1);
	  }
  }
  }

2021/4/15

知识点

  • 数组的操作(虽然在前两次的作业里面也用过很多次数组了)
  • method:trim,用来去String的开头和结尾的空白
  • 接上条:字符数组可能会有blankspace从而导致WA

1

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
	public static void printArray(int[] array) {
		 System.out.print('<');
		 for ( int i = 0; i < array.length; i++ ) { 
		 // print an element
		 System.out.print(array[i]); 
		 // print a comma delimiter if not the last element 
		 if ( (i + 1) < array.length ) { 
		 System.out.print(", "); 
		 }
		 }
		 System.out.println('>');
		} 
  public static void main(String[] args){
	  int[] array1= {2, 3, 5, 7, 11, 13, 17,19};
	  printArray(array1);
	  int[] array2=array1;
	  int len=array1.length;
	  for(int i=0;i<len;i++)
		  if(i%2==0)array2[i]=i;
	  printArray(array2);
	  int[][]matrix=new int[5][];
	  for(int i=0;i<5;i++)
		  {
		  matrix[i]=new int[i];
		  for(int j=0;j<i;j++)
			  matrix[i][j]=i*j;
		  }
	  for(int i=0;i<5;i++)
	  {
		  System.out.print("matrix["+i+"] is ");
		  printArray(matrix[i]);
	  }
  }
  }

2

package x;
import java.text.DecimalFormat;
import java.util.*;
class Bank{
	private int numberOfCustomers;
	private char customers[][];
	public Bank(int num)
	{
		numberOfCustomers=num;
		customers=new char[15][15];
	}
	public int getNumOfCustomers()
	{
		return numberOfCustomers;
	}
	public void addCustomer(String fn,String ln)
	{
		int i;
		int len1=fn.length(),len2=ln.length();
		for(i=0;i<len2;i++)
			customers[numberOfCustomers][i]=ln.charAt(i);
		customers[numberOfCustomers][i]=',';
		i++;
		for(;i<len1+len2+1;i++)
		{
			customers[numberOfCustomers][i]=fn.charAt(i-len2-1);
		}
		numberOfCustomers++;
	}
	public char[] getCustomer(int i)
	{
        return customers[i];
	}
}
public class x{
  public static void main(String[] args){
	  Scanner in=new Scanner(System.in);
	  int l=in.nextInt();
	  String fn,ln;
	  Bank bank=new Bank(0);
	  for(int i=0;i<l;i++)
	  {
		  fn=in.next();
		  ln=in.next();
		  bank.addCustomer(fn, ln);
	  }
	  for(int i=0;i<bank.getNumOfCustomers();i++)
	  {
		  int t=i+1;
		  System.out.print("Customer ["+t+"] is ");
		  System.out.println(bank.getCustomer(i));
	  }
	  in.close();
  }
}

3

package x;
import java.text.DecimalFormat;
import java.util.*;
class Account{
	private double balance;//存储余额
	public Account(double blc) {
		balance=blc;
	}
	public double getBalance()
	{
		return balance;
	}
	public boolean deposit(double amt)
	{
		balance+=amt;
		return true;
	}
	public boolean withdraw(double amt)
	{
		if(balance>=amt)
		{
		balance-=amt;
		return true;
		}
		else return false;
	}
}
class Customer {
	private String lastname,firstname;
	private Account account;
	public Customer(String fn,String ln)
	{

		firstname=fn;
		lastname=ln;
	}
	public String getFirstName()
	{
		return firstname;
	}
	public String getLastName()
	{
		return lastname;
	}
	public void setAccount (Account acc)
	{
		account=acc;
	}
	public Account getAccount()
	{
		return account;
	}
}
public class x{
  public static void main(String[] args){
	  Customer customer;
	  Account account;
	  // Create an account that can has a 500.00 balance.
	  System.out.println("Creating the customer Jane Smith.");
	  customer = new Customer("Jane", "Smith");
	  System.out.println("Creating her account with a 500.00 balance.");
	  customer.setAccount(new Account(500.00));
	  account = customer.getAccount();
	  // Perform some account transactions
	  System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
	  System.out.println("Deposit 22.50: " + account.deposit(22.50));
	  System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
	  System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
	  // Print out the final account balance
	  System.out.println("Customer [" + customer.getLastName()
	  + ", " + customer.getFirstName()
	  + "] has a balance of " + account.getBalance());
  }
}

4

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 int num1=in.nextInt();
	 int num2=in.nextInt();
	 int min=num1<num2?num1:num2;
	 int divisor=1;
	 for(int i=1;i<=min;i++)
	 {
		 if((num1%i==0)&&(num2%i==0))divisor=i;
	 }
	 int multiple=num1*num2/divisor;
	 System.out.print(divisor+" ");
	 System.out.println(multiple);
  }
}

5

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 int n=in.nextInt();
	 String origin[]=new String[n];
	 for(int i=0;i<n;i++)
	 {
		origin[i]=in.next();
	}
	 int m=in.nextInt();
	 for(int i=0;i<n;i++)
	 {
		 int len=origin[i].length();
		 char vary[]=new char[len];
		 int j;
		 for(j=0;j<len;j++)
		 {   
			int k=(j+m)%len;
			 vary[k]=origin[i].charAt(j);
		 }
		 if(vary[0]=='0')
		 {
			 for(j=1;j<len-1;j++)
					System.out.print(vary[j]);
				System.out.println(vary[j]); 
		 }
		 else{
			 for(j=0;j<len-1;j++)
			System.out.print(vary[j]);
		System.out.println(vary[j]);
	 }
	 }
	
  }
}

6

package x;

import java.text.DecimalFormat;
import java.util.*;
class Gift{
	 String name;
	 int money;
}
public class x{
  public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 int n=in.nextInt();
	 Gift NP[]=new Gift[n];
	 for(int i=0;i<n;i++)
		 NP[i]=new Gift();
	 for(int i=0;i<n;i++)NP[i].money=0;
	 for(int i=0;i<n;i++)
		 NP[i].name=in.next();
	int amount,NGi;
	String giver=in.next();
	amount=in.nextInt();
	NGi=in.nextInt();
	String name;
    while(NGi!=0){ 
	for(int i=0;i<n;i++)
	{
	 if(NP[i].name.equals(giver))
	  {int minus=amount/NGi;
	  minus=minus*NGi;
	   NP[i].money-=minus;
	  }
	}
	int mean=amount/NGi;
	for(int j=0;j<NGi;j++)
	{
		name=in.next();
		for(int i=0;i<n;i++)
		{
			if(NP[i].name.equals(name))
				{
				NP[i].money+=mean;
				}
		}
	}
	giver=in.next();
	amount=in.nextInt();	
	NGi=in.nextInt();
	};
	for(int i=0;i<n;i++)
	System.out.println(NP[i].name+" "+NP[i].money);
  }
}

7

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 String s1=in.next();
	 String s2=in.next();
	 String s3=in.next();
	 char prefix[]=new char[10];
	 int len1,len2,len3;
	 len1=s1.length();
	 len2=s2.length();
	 len3=s3.length();
	 int min;
	 min=len1<len2?len1:len2;
	 min=min<len3?min:len3;
	 for(int i=0;i<min;i++)
	 {
		 if((s1.charAt(i)==s2.charAt(i))&&(s2.charAt(i)==s3.charAt(i)))
				 prefix[i]=s1.charAt(i);
		 else {
			 break;
		 }
	 }
	 System.out.println(prefix);
  }
}

8

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
  public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 String s=in.next();
	 char exam[]=new char[20];
	 int k=0;
	 int t=0;
	 for(int i=0;i<s.length();i++)
	 {
		 if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
		 {
			 exam[k]=s.charAt(i);
			 k++;		 
		 }
		 else if((s.charAt(i)==']'||s.charAt(i)==')'||s.charAt(i)=='}')&&i!=0)
		 {
			 switch(s.charAt(i))
			 {
			 case ')':{
				 if(exam[k-1]=='(')k--;
				 break;
			 }
			 case '}':{
				 if(exam[k-1]=='{')k--;
				 break;
			 }
			 case ']':{
				 if(exam[k-1]=='[')k--;
				 break;
			 }
			 }
		 }
		 else {t=1;break;}
	}
	 if(k==0&&t!=1)System.out.println("True");
	 else System.out.println("False");
  }
}

2021/4/30

知识点

hashset

					HashSet<String> sites1 = new HashSet<String>();
                	HashSet<String> sites2 = new HashSet<String>();
                    Set<String> result = new HashSet<String>();
*存入hashset
                    for(int i=0;i<len1;i++)sites1.add(s1[i]);
                    for(int i=0;i<len2;i++)sites2.add(s2[i]);
* 求补集                	
                	    result.clear();
                	    result.addAll(sites1);
                	    result.addAll(sites2);
                	    String  r=result.toString();
                	    r=r.replace("[", "").replace("]", "");
                	    System.out.println(r);
              
*求差集                	   
                	    result.clear();
                        result.addAll(sites1);
                        result.removeAll(sites2);
                        r=result.toString();
                        r=r.replace("[", "").replace("]", "");
                        System.out.println(r);
* 求交集                	    
                    result.clear();
                    result.addAll(sites1);
                    result.retainAll(sites2);
                     r=result.toString();
                    r=r.replace("[", "").replace("]", "");
                    System.out.println(r);

hashmap

  Map<String, Integer> map = new HashMap<String, Integer>();
  for (int i = 0; i < textArray.length; i++) {
   String key = textArray[i];
   //转为小写
   String key_l = key.toLowerCase();
   if(!"".equals(key_l)){
    Integer num = map.get(key_l);  //得到key对应的value值
    if(num == null || num == 0){
     map.put(key_l, 1);//存放到map中
    }else if(num > 0){
     map.put(key_l, num+1);
    }
   }
  }

List

							List<Character> list = new ArrayList<Character>();
                			list.add(str.charAt(0));
                			for(int i=1;i<str.length();i++) {
                				if(list.contains(str.charAt(i))) {
*返回与当前字符相同字符的索引               		
                					int index = list.indexOf(str.charAt(i)); 
 *求子list
                					list = list.subList(index+1, list.size());
*list添加元素
                					list.add(str.charAt(i));
                					maxLength = Math.max(maxLength, list.size());
                				}else {
                					list.add(str.charAt(i));
                					maxLength = Math.max(maxLength, list.size());
                				}
                			}

排序

  Collections.sort(list, (o1, o2) -> (o2.getValue() - o1.getValue()));
 userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Course :: getid))), ArrayList::new));

1

package x;
import java.text.DecimalFormat;
import java.util.*;
class PhoneNumber{
}
public class x{
	public static void main(String[] args){
	Scanner in= new Scanner(System.in);
	int[] array=new int [5];
	for(int i=0;i<5;i++)array[i]=in.nextInt();
	 //for循环
	int i=0;
	 for(i=0;i<4;i++)System.out.print(array[i]+" ");
	 System.out.println(array[i]);
	 //foreach
	 for(int s:array) {
		 if(s!=array[4])System.out.print(s+" ");
	 }
	 System.out.println(array[4]);
	//String
	String x=Arrays.toString(array).replace("[", "").replace("]", "").replace(",", "");
	System.out.println(x);
  }	
}

2

package x;
import java.text.DecimalFormat;
import java.util.*;
class Bank{
	private int ID;
	private String Name;
	private double Balance;
	Bank(){}
	void getid(int id)
	{
		ID=id;
	}
	void getname(String name)
	{
		Name=name;
	}
	void getbalance(double balance)
	{
		Balance=balance;
	}
	void show()
	{
		System.out.println("ID:"+ID+", Name:"+Name+", Balance:"+Balance);
	}
}
public class x{
	public static void main(String[] args){
	Scanner in= new Scanner(System.in);
	int n=in.nextInt();
	Bank[] info=new Bank[n];
	for(int i=0;i<n;i++)info[i]=new Bank();
	for(int i=0;i<n;i++)
	{
		info[i].getid(in.nextInt());
		info[i].getname(in.next());
		info[i].getbalance(in.nextDouble());
	}
	for(int i=0;i<n;i++)
		info[i].show();
  }	
}

3

package x;
import java.text.DecimalFormat;
import java.util.*;
public class x{
    static String Type(String s)
    {
    	char[] PhoneType=new char[8];
    	int i=0;
    	for(int j=0;j<s.length();j++)
    	{
    		//System.out.println("l:"+s.length());
    		//System.out.println("i:"+i);
    	    //System.out.println("j:"+j);
    		//System.out.println("s["+j+"]:"+s.charAt(j));
    		if(i!=3) {
    		switch(s.charAt(j)) {
    		case 'A':
    		case 'B':
    		case 'C':
    			PhoneType[i]='2';
    			i++;
    		    break;
    		case 'D':
    		case 'E':
    		case 'F':
    			PhoneType[i]='3';
    			i++;
    		    break;
    		case 'G':
    		case 'H':
    		case 'I':
    			PhoneType[i]='4';
    			i++;
    		    break;
    		case 'J':
    		case 'K':
    		case 'L':
    			PhoneType[i]='5';
    			i++;
    		    break;
    		case 'M':
    		case 'N':
    		case 'O':
    			PhoneType[i]='6';
    			i++;
    		    break;
    		case 'P':
    		case 'R':
    		case 'S':
    			PhoneType[i]='7';
    			i++;
    		    break;
    		case 'T':
    		case 'U':
    		case 'V':
    			PhoneType[i]='8';
    			i++;
    		    break;
    		case 'W':
    		case 'X':
    		case 'Y':
    			PhoneType[i]='9';
    			i++;
    		    break;
    		case'-':break;
    		default:
    		{
    			PhoneType[i]=s.charAt(j);
    		     i++;
    		}
    		}
    	 }
    		else if(i==3) {
    			PhoneType[i]='-';
    		    i++;
    		    j--;
    		}
    		//if(i!=0)
    		//System.out.println("PhoneType["+(i-1)+"]:"+PhoneType[i-1]);
    	}
		return String.valueOf(PhoneType);
    	
    }
	public static void main(String[] args){
	 Scanner in=new Scanner(System.in);
	 int n=in.nextInt();
	 String[] PhoneNumber=new String [n];
	 String[] PhoneType=new String [n];
	 for(int i=0;i<n;i++)
	 {
		 PhoneNumber[i]=in.next();
		 PhoneType[i]=Type(PhoneNumber[i]);
	 }
	 //for(int i=0;i<n;i++)System.out.println(PhoneType[i]);
	 int[] phone=new int [n];
	 for(int i=0;i<n;i++)
		 phone[i]=Integer.parseInt(PhoneType[i].replaceAll("-", ""));
	 int[] count=new int [10000000];
	 for(int i=0;i<10000000;i++)count[i]=0;
	 for(int i=0;i<n;i++)count[phone[i]]++;
	 for(int i=0;i<10000000;i++)
	 {
		 if(count[i]>=2) {
			 String s=String.valueOf(i);
			 StringBuffer x =new StringBuffer(s);
			 x=x.insert(3,"-");
			 System.out.println(x+" "+count[i]);}
	 }
}
}

4

package x;
import java.text.DecimalFormat;
import java.util.*;
import java.util.HashSet; // 引入 HashSet 类
import java.util.HashMap;
                public class x{
                	public static void main(String[] args){
                		Scanner in=new Scanner(System.in);
          		        String line1 = in.nextLine();
          		        int blank=0;
          		        for(int i=0;i<line1.length();i++)  
          		        {   
          		        if(line1.charAt(i)==32)   
          		         blank++;   
          		        }
          		        int len1=blank+1;
                          String [] s1 = line1.split("\\s+");
            		     
                          String line2 = in.nextLine();
            		        int blank2=0;
            		        for(int i=0;i<line2.length();i++)  
            		        {   
            		        if(line2.charAt(i)==32)   
            		         blank2++;   
            		        }
            		        int len2=blank2+1;
                         String [] s2 = line2.split("\\s+");
                         
                	HashSet<String> sites1 = new HashSet<String>();
                	HashSet<String> sites2 = new HashSet<String>();
                    Set<String> result = new HashSet<String>();
                    for(int i=0;i<len1;i++)sites1.add(s1[i]);
                    for(int i=0;i<len2;i++)sites2.add(s2[i]);
                	
                	    result.clear();
                	    result.addAll(sites1);
                	    result.addAll(sites2);
                	    String  r=result.toString();
                	    r=r.replace("[", "").replace("]", "");
                	    System.out.println(r);
              
                	   
                	    result.clear();
                        result.addAll(sites1);
                        result.removeAll(sites2);
                        r=result.toString();
                        r=r.replace("[", "").replace("]", "");
                        System.out.println(r);
                	    
                    result.clear();
                    result.addAll(sites1);
                    result.retainAll(sites2);
                     r=result.toString();
                    r=r.replace("[", "").replace("]", "");
                    System.out.println(r);

                   
                }
				
}

5

import java.util.*;

public class Main{
 public static void findEnglishNum(String text){
  //找出所有的单词
  String[] array = {".", " ", "?", "!"};
  for (int i = 0; i < array.length; i++) {
   text = text.replace(array[i],",");
  }
  String[] textArray = text.split(",");
  
  //遍历 记录
  Map<String, Integer> map = new HashMap<String, Integer>();
  for (int i = 0; i < textArray.length; i++) {
   String key = textArray[i];
   //转为小写
   String key_l = key.toLowerCase();
   if(!"".equals(key_l)){
    Integer num = map.get(key_l);
    if(num == null || num == 0){
     map.put(key_l, 1);
    }else if(num > 0){
     map.put(key_l, num+1);
    }
   }
  }
  List<Map.Entry<String, Integer>> list0 = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); //转换为list
   list0.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getKey().compareTo(o1.getKey());
            }
        });
   
   Collections.sort(list0, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getKey().compareTo(o1.getKey());
            }
        });
   int q = 0;
   for(Map.Entry<String, Integer> str : list0) {
    q++;
    if(q != map.size())
    System.out.print(str.getKey() + "=" + str.getValue() + ", ");
   else
    System.out.print(str.getKey() + "=" + str.getValue());
     
    }
   System.out.println();
  //输出到控制台
  
 }

   public static void main(String[] args)
       {
           Scanner sc = new Scanner(System.in);
     String s = sc.nextLine();
     findEnglishNum(s);
     

       }
}

6

package x;
import java.text.DecimalFormat;
import java.util.*;
import java.util.HashSet; // 引入 HashSet 类
import java.util.HashMap;
                public class x{
                	public static void main(String[] args){
                		Scanner in=new Scanner(System.in);
                	    String s=in.next();
                	    System.out.println(lengthOfLongestSubstring(s));
                	}
                		public static int lengthOfLongestSubstring(String str) {
                			if(str.length()==0)
                				return 0;
                			
                			int maxLength=1;
                			List<Character> list = new ArrayList<Character>();
                			list.add(str.charAt(0));
                			for(int i=1;i<str.length();i++) {
                				if(list.contains(str.charAt(i))) {
                					//返回与当前字符相同字符的索引
                					int index = list.indexOf(str.charAt(i)); 
                					list = list.subList(index+1, list.size());
                					list.add(str.charAt(i));
                					maxLength = Math.max(maxLength, list.size());
                				}else {
                					list.add(str.charAt(i));
                					maxLength = Math.max(maxLength, list.size());
                				}
                			}
                			return maxLength;
                		}
                }
				

7

package x;
import java.text.DecimalFormat;
import java.util.*;
import java.util.HashSet; // 引入 HashSet 类
import java.util.HashMap;
public class x{
	

	public static void main(String[] args){
		

        //给定字符串
        Scanner in=new Scanner(System.in);
        String line = in.nextLine();
        line=line.toLowerCase();
        int blank=0;
        for(int i=0;i<line.length();i++)  
        {   
        if(line.charAt(i)==32)   
         blank++;   
        }
        int len=blank+1;
        String [] s = line.split("\\s+");
        HashMap<String, Integer> hashMap = new HashMap<>();//key-value:字符-出现次数
        
        for (int i = 0; i < len; i++) {
		    String sub = s[i];
		    //如果map中没有此字符,则次数置为1
		    if (!hashMap.containsKey(sub)) {
		        hashMap.put(sub, 1);
		    } else {
		        //如果map中有此字符,则次数增1
		        Integer temNum = hashMap.get(sub);
		        temNum++;
		        hashMap.put(sub, temNum);
		    }
		}
        List<Map.Entry<String,Integer>> list = new ArrayList(hashMap.entrySet());
        Collections.sort(list, (o1, o2) -> (o2.getValue() - o1.getValue()));
        if(!list.get(1).getKey().equals("0")) 
        System.out.println(list.get(0).getKey()+" "+list.get(1).getKey());
        else System.out.println(list.get(0).getKey());
}
}

8

import java.text.DecimalFormat;
import java.util.*;
import java.util.HashSet; // 引入 HashSet 类
import java.util.HashMap;
public class x{
	//根据value值获取到对应的一个key值
    public static String getKey(LinkedHashMap<String,String> map,String fri){
        String key = null;         
        //Map,HashMap并没有实现Iteratable接口.不能用于增强for循环.
        for(String getKey: map.keySet()){
            if(map.get(getKey).equals(fri)){
                key = getKey;
            }
        }
        return key;
        //这个key肯定是最后一个满足该条件的key.
    }
    public static String DingZhen(LinkedHashMap<String,String> map)
    {
    	String fri="1";
    	for(String key:map.keySet())
    	{
    		if(key.equals(fri))fri=map.get(fri);
    		
    		System.out.println("key:"+key);
    		System.out.println("values:" +map.get(key));
    		if(map.get(key).equals(fri))fri=key;
    		System.out.println("fri: "+fri);
    	}
    	return fri;
    }

	public static void main(String[] args){
		
		        //给定字符串
		        Scanner in=new Scanner(System.in);
		        int n=in.nextInt();
		        for(int i=0;i<n;i++) {
		        	int m=in.nextInt();
			        String[] opt=new String [m];	
			        LinkedHashMap<String, String> sites = new LinkedHashMap<>();//key-value:字符-出现次数
			       String fri="1";
		       for(int j=0;j<m;j++) {
		        opt[i]=in.next();
                String [] s = opt[i].split("-");
                if(s[0].equals(fri))fri=s[1];
                else if(s[1].equals(fri))fri=s[0];
                //System.out.println(" ");
                //System.out.println(s[0]+" "+s[1]);
		       // sites.put(s[0], s[1]);
		        	}
		       System.out.println(fri);
		        }
}
}

9

package x;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;
class Course{
	int Id;
	String Name;
	int time;
	int score;
	 Course(int id,String name,int t,int s)
	 {
		 Id=id;
		 Name=name;
		 time=t;
		 score=s;
	 }
	 public int getid()
	 {
		 return Id;
	 }
	 @Override
	    public String toString() {
	        return Id + "," +Name+","+time+"," + score;
	    }
	}
    public class x{
      public static void main(String[] args){
    	  List<Course> userList = new ArrayList<>();
          userList.add(new Course(1, "College Advanced Mathematics", 64,4));
          userList.add(new Course(2, "College Physical Education", 36,1));
          userList.add(new Course(3, "Java programming", 48,3));
          userList.add(new Course(4, "English reading and writing AI", 32,2));
          userList.add(new Course(4,"English reading and writing AI", 32,2));
          userList.add(new Course(5, "form and policy", 96,2));    //id相同,其他数据也相同
          for(int i=0;i<6;i++)if(userList.get(i).score>2)System.out.print(userList.get(i));
          System.out.println();
          userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Course :: getid))), ArrayList::new));
          String str = userList.toString().replaceAll("(?:\\[|null|\\]| +)", "");
          System.out.println(str);
          
      }
    }

10

package x;
import java.text.DecimalFormat;
import java.util.*;
import java.util.HashSet; // 引入 HashSet 类
import java.util.HashMap;
public class x{
	public static void main(String[] args){
		Scanner in=new Scanner(System.in);
		String []s=new String[105];
		HashSet<String> se = new HashSet<String>();
		int m,n;
		String c;
		n=in.nextInt();
		m=in.nextInt();
		c=in.next();
			for (int i=0;i<n;i++)
				s[i]=in.next();//样例中没有空格,所以要整行的读入
			for (int i=0;i<n;i++)
				for (int j=0;j<m;j++)
					if (s[i].charAt(j)==c.charAt(0))
					{
						if (s[i].charAt(j+1)!=c.charAt(0)&&s[i].charAt(j+1)!='.'&&j+1<m) se.add(String.valueOf(s[i].charAt(j+1)));
						if (s[i].charAt(j-1)!=c.charAt(0)&&s[i].charAt(j-1)!='.'&&j-1>=0) se.add(String.valueOf(s[i].charAt(j-1)));
						if (s[i-1].charAt(j)!=c.charAt(0)&&s[i-1].charAt(j)!='.'&&i-1>=0) se.add(String.valueOf(s[i-1].charAt(j)));
						if (s[i+1].charAt(j)!=c.charAt(0)&&s[i+1].charAt(j)!='.'&&i+1<n)se.add(String.valueOf(s[i+1].charAt(j)));
						//上下左右依次判断由于
					}
			System.out.println(se.size()); //由于在前面已经加入过set中了,可以直接用size()来取长度
}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值