【SA】JAVA语言程序设计 C4-C5

C4 数学函数、字符和字符串

修改彩票程序

输入产生两位随机字符串代替数字,使用字符串接受用户的输入

import java.util.*;

public class test {
    public static void main(String[] args) {
        String lottery = "" + (int)(Math.random()* 10)
           + (int)(Math.random()* 10);

        Scanner input = new Scanner(System.in);
        System.out.print("Enter your lottery pick (two digits):");
        String guess = input.nextLine();

        char lotteryD1 = lottery.charAt(0);
        char lotteryD2 = lottery.charAt(1);

        char guessD1 = guess.charAt(0);
        char guessD2 = guess.charAt(1);

        System.out.println("The lottery number is " + lottery);

        if (guess.equals(lottery))
            System.out.println("Exact match: you win $10,000");

        else if((lotteryD1 == guessD2)
                && (lotteryD2 == guessD1)) {
            System.out.println("Match all digits,you win $3000  " );
        }

        else if((lotteryD1 == guessD1)
                || (lotteryD1 == guessD2)
                || (lotteryD2 == guessD1)
                || (lotteryD2 == guessD2)) {
            System.out.println("Match all digits,you win $1000  " );
        }
        else
            System.out.println("sorry no match " );
    }
}

//Enter your lottery pick (two digits):00 
//The lottery number is 59
//sorry no match

4.5 几何:正多边形的面积

正多边形是一个具有n条边的多边形,它每条边的长度都相等,而且所有角的度数也相等(即多边形既等边又等角)。
这里,s是边长。编写一个程序,提示用户输入边的个数以及正多边形的边长,然后显示它的面积。

import java.util.*;

public class test {
    public static void main(String[] args) {
        int numberOfSide;
        double area, side;

        System.out.print("Enter the number of sides:");
        Scanner input = new Scanner(System.in);
        numberOfSide = input.nextInt();
        System.out.print("Enter the side;");
        side = input.nextDouble();
        area = (numberOfSide * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / numberOfSide));

        System.out.printf("The area of the hexagon is %5.4f", area);
        input.close();
    }
}
//Enter the number of sides:6
//Enter the side;6
//The area of the hexadon is 93.5307

4.21 检查 SSN

编写一个程序,提示用户输入一个社保号码,它的格式是DDD-DD-DDDD,其中D是一个数字。你的程序应该判断输入是否合法。
下面是一个运行示例:
Enter a SSN: 232-23-5435
232-23-5435 is a valid social security number
Enter a SSN: 23-23-5435
23-23-5435 is an invalid social security number

import java.util.*;

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

        System.out.print("Enter a SSN: ");
        Scanner input = new Scanner(System.in);
        String ssnString = input.nextLine();

        if (ssnString.length() == 11)
        {
            if (Character.isDigit(ssnString.charAt(0))
                    && Character.isDigit(ssnString.charAt(1))
                    && Character.isDigit(ssnString.charAt(2))
                    && ssnString.charAt(3) == '-'
                    && Character.isDigit(ssnString.charAt(4))
                    && Character.isDigit(ssnString.charAt(5))
                    && ssnString.charAt(6) == '-'
                    && Character.isDigit(ssnString.charAt(7))
                    && Character.isDigit(ssnString.charAt(8))
                    && Character.isDigit(ssnString.charAt(9))
                    && Character.isDigit(ssnString.charAt(10)))
                System.out.println(ssnString + " is a valid social security number");
            else
                System.out.println(ssnString + " is an invalid social security number");

        }
        else
            System.out.println(ssnString + "is an invalid social security number");
        input.close();
    }
}

//Enter a SSN: 123-45-6666
//123-45-6666 is a valid social security number

4.26 金融应用:货币单位

重写程序清单2-10,解决将float型值转换为int型值时可能会造成精度损失的问题。读取的输入值是一个字符串,比如“11.56”。你的程序应该应用indexOf和substring方法提取小数点前的美元数量,以及小数点后的美分数量。

import java.util.*;

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

        Scanner input = new Scanner(System.in);

        // Receive the amount
        System.out.print("Enter an amount in double, for example 11.56: ");
        String amount = input.nextLine();
     	//精华两句
        int remainingAmount = (int)(Integer.parseInt(amount.substring(0, amount.indexOf('.'))) * 100
                + Integer.parseInt(amount.substring(amount.indexOf('.')+1)));

        // Find the number of one dollars
        int numberOfOneDollars = remainingAmount / 100;
        remainingAmount = remainingAmount % 100;

        // Find the number of quarters in the remaining amount
        int numberOfQuarters = remainingAmount / 25;
        remainingAmount = remainingAmount % 25;

        // Find the number of dimes in the remaining amount
        int numberOfDimes = remainingAmount / 10;
        remainingAmount = remainingAmount % 10;

        // Find the number of nickels in the remaining amount
        int numberOfNickels = remainingAmount / 5;
        remainingAmount = remainingAmount % 5;

        // Find the number of pennies in the remaining amount
        int numberOfPennies = remainingAmount;

        // Display results
        System.out.println("Your amount " + amount + " consists of");
        System.out.println(" " + numberOfOneDollars + " dollars");
        System.out.println(" " + numberOfQuarters + " quarters ");
        System.out.println(" " + numberOfDimes + " dimes");
        System.out.println(" " + numberOfNickels + " nickels");
        System.out.println(" " + numberOfPennies + " pennies");

        input.close();
    }
}
//Enter an amount in double, for example 11.56: 22.777
//Your amount 22.777 consists of
// 29 dollars
// 3 quarters 
// 0 dimes
// 0 nickels
// 2 pennies

C5 循环

3种循环

例子:循环打印100次
1、while循环

初始化语句
      while(循环继续条件) {
       //循环体
       语句(组);
      }
      
      eg:
   		int count = 0
   		while(count < 100) {
   		System.out.printIn("Welcome to JAVA!");
   		count++;
   		}
   		

2、do while

初始化语句
       do(循环体){
       //循环体
       语句(组);
      } while(循环继续条件)
      
      eg:
   		int count = 0
   		 do {
   		System.out.printIn("Welcome to JAVA!");
   		count++;
   		} while(count < 100);
   		

3、for循环

       for(初始操作;循环继续条件;每次迭代后的操作){
       //循环体
       语句(组);
      } 
      
      eg:
   		 for (int i = 0; i <100; i++){
   		System.out.printIn("Welcome to JAVA!");
   		} 

打印99乘法表

嵌套循环

import java.util.*;

public class test {
    public static void main(String[] args) {
        System.out.println("Multiplication Table");

        System.out.print("  ");
        for (int j = 1; j <= 9; j++)
            System.out.print("   " + j);
        System.out.println("\n----------------------------------------");

        for (int i = 1; i <= 9; i++) {
            System.out.print(i + " |");
            for (int j = 1; j <= 9; j++) {
                System.out.printf("%4d", i * j);
            }
            System.out.println();
        }
    }
}

//Multiplication Table
//     1   2   3   4   5   6   7   8   9
//----------------------------------------
//1 |   1   2   3   4   5   6   7   8   9
//2 |   2   4   6   8  10  12  14  16  18
//3 |   3   6   9  12  15  18  21  24  27
//4 |   4   8  12  16  20  24  28  32  36
//5 |   5  10  15  20  25  30  35  40  45
//6 |   6  12  18  24  30  36  42  48  54
//7 |   7  14  21  28  35  42  49  56  63
//8 |   8  16  24  32  40  48  56  64  72
//9 |   9  18  27  36  45  54  63  72  81

5.14 示例学习-显示素数

要求:分5行显示前50个素数,每行包含10个数字

分解:
1、判断一个给定数是否是素数。
2、针对number = 1、2、3等测试
3、统计素数个数
4、打印每个素数,每行打印10个

算法:

设置打印出的素数个数常量NUMBER_OF_PRIMES;
使用count来对素数个数计数并初始值设置为0;
number初始值为2while(count <NUMBER_OF_PRIMES){
测试该数是否为素数;
	if 该数是素数{
		打印该素数并给count增加1}
给number 加1}
public class test {
    public static void main(String[] args) {
        final int NUMBER_OF_PRIMES = 50;
        final int NUMBER_OF_PRIMES_PER_LINE = 10;
        int count = 0;
        int number = 2;

        System.out.println("The first 50 prime numbers are \n");

        //Repeatedly find prime numbers
        while (count < NUMBER_OF_PRIMES) {
            //Assume the number is prime
            boolean isPrime = true; //Is the current number prime?

            //Test whether number is prime
            for(int divisor = 2; divisor <= number / 2; divisor++) {
                if(number % divisor == 0) {//if true, number is not prime
                    isPrime = false;//Set isPrime to false
                    break;//Exit the for loop
                }
            }
            //Display the prime number and increase the count
            if(isPrime) { 
                count++;//Increase the count

                if(count % NUMBER_OF_PRIMES_PER_LINE == 0){
                    //Display the number and advance to the neww line
                    System.out.println(number);
                        }
                else
                    System.out.print(number + "");
            }

            //Check if the next number is prime
            number++;
        }
    }
}

//The first 50 prime numbers are 
//
//2357111317192329
//31374143475359616771
//7379838997101103107109113
//127131137139149151157163167173
//179181191193197199211223227229

5.19 打印金字塔型数字

编写一个嵌套的for循环,打印下面的输出:

                            1

                        1  2  1

                    1  2  4  2  1

                1  2  4  8  4  2  1

            1  2  4  8  16  8  4  2  1

        1  2  4  8  16  32  16  8  4  2  1

    1  2  4  8  16  32  64  32  16  8  4  2  1

1  2  4  8  16  32  64  128  64  32  16  8  4  2  1
public class test {
    public static void main(String[] args) {

        for(int line = 8;line >= 1;line--)
        {
            for(int i = 1;i <= 4 * (line-1);i++)
                System.out.print(" ");
            for(int i = 1;i <= (9 - line);i++)
                System.out.printf("%4d",(int)Math.pow(2, i-1));
            for(int i = (8 - line);i >= 1;i--)
                System.out.printf("%4d",(int)Math.pow(2, i-1));
            System.out.print("\n");
        }
    }
}

5.50 对大写字母计数

编写一个程序,提示用户输入一个字符串,然后显示该字符串大写字母的数目。
Enter a string: Welcome to Java
The number of uppercase letters is 2

import java.util.*;

public class test {
	public static void main(String[] args) {
		String userString;
		int upperLetterCount = 0;
		
		Scanner inputScanner = new Scanner(System.in);
		System.out.print("Enter a string: ");
		userString = inputScanner.nextLine();
		
		for(int strIndex = 0;strIndex < userString.length();strIndex++)
			if(userString.charAt(strIndex) >= 65 && userString.charAt(strIndex) <= 90)
				upperLetterCount++;
		System.out.printf("The number of uppercase letters is %d", upperLetterCount);
		
		inputScanner.close();
	}
}

5.34 游戏:石头、剪刀、布

编程练习题3.17给出玩石头—剪刀—布游戏的程序。修改这个程序,让用户可以连续地玩这个游戏,直到用户或者计算机赢对手两次以上为止。

思路:

        //定义
        int userWin,computerWin;
        userWin = computerWin = 0;
        Scanner input = new Scanner(System.in);
        
		//大循环:user or cpmputer win less than 2 times
        while(userWin <= 2 && computerWin <= 2)
        {
            //定义:the range of random int is 0 to 2
            int userGuess,computerGuess = (int)(Math.random()*3);
            
            System.out.print("scissor(0),rock(1),paper(2): ");
            userGuess = input.nextInt();

            // Check user's guess and Display the result
            if(computerGuess == 0)
            // computerguess contains 3 situation	
           { 
             //1-3
            {
            }
           }
            else if(computerGuess == 1) 
          {
            }
            else 
            {
            }
         }
            // Display invalid situation
            if(userGuess > 2 || userGuess < 0)
            {
               打印错误
            }
        }
		游戏结束,打印结果

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        int userWin,computerWin;
        userWin = computerWin = 0;
        Scanner input = new Scanner(System.in);


        while(userWin <= 2 && computerWin <= 2)
        {
            int userGuess,computerGuess = (int)(Math.random()*3);

            // Prompt the user to enter a guess
            System.out.print("scissor(0),rock(1),paper(2): ");
            userGuess = input.nextInt();

            // Check user's guess and Display the result
            if(computerGuess == 0)	// The situation that computer guess is a scissor
            {
                if(userGuess == 0)
                {
                    System.out.println("The computer is scissor.");
                    System.out.println("You are scissor too.");
                    System.out.println("It is a draw");
                }
                else if(userGuess == 1)
                {
                    System.out.println("The computer is scissor.");
                    System.out.println("You are rock.");
                    System.out.println("You won");
                    userWin++;
                }
                else if(userGuess == 2)
                {
                    System.out.println("The computer is scissor.");
                    System.out.println("You are paper.");
                    System.out.println("You lost");
                    computerWin++;
                }
            }
            else if(computerGuess == 1) // The situation that computer guess is a rock
            {
                if(userGuess == 0)
                {
                    System.out.println("The computer is rock.");
                    System.out.println("You are scissor.");
                    System.out.println("You lost");
                    computerWin++;
                }
                else if(userGuess == 1)
                {
                    System.out.println("The computer is rock.");
                    System.out.println("You are rock too.");
                    System.out.println("It is a draw");
                }
                else if(userGuess == 2)
                {
                    System.out.println("The computer is rock.");
                    System.out.println("You are paper.");
                    System.out.println("You won");
                    userWin++;
                }
            }
            else //The situation that computer guess is a paper
            {
                if(userGuess == 0)
                {
                    System.out.println("The computer is paper.");
                    System.out.println("You are scissor.");
                    System.out.println("You won");
                    userWin++;
                }
                else if(userGuess == 1)
                {
                    System.out.println("The computer is paper.");
                    System.out.println("You are rock.");
                    System.out.println("You lost");
                    computerWin++;
                }
                else if(userGuess == 2)
                {
                    System.out.println("The computer is paper.");
                    System.out.println("You are paper too.");
                    System.out.println("It is a draw");
                }
            }

            // Display invalid situation
            if(userGuess > 2 || userGuess < 0)
            {
                System.out.println("Error:Invalid Guess");
                System.exit(1);
            }
        }
        System.out.println("The game is over.");
        System.out.printf("You total won %d times\n", userWin);
        System.out.printf("Computer total won %d times\n", computerWin);

        input.close();
    }
}

s1:
//scissor(0),rock(1),paper(2): 3
//Error:Invalid Guess

s2:
// scissor(0),rock(1),paper(2): 1
//        The computer is scissor.
//        You are rock.
//        You won
//        scissor(0),rock(1),paper(2): 1
//        The computer is paper.
//        You are rock.
//        You lost
//        scissor(0),rock(1),paper(2): 1
//        The computer is paper.
//        You are rock.
//        You lost
//        scissor(0),rock(1),paper(2): 1
//        The computer is rock.
//        You are rock too.
//        It is a draw
//        scissor(0),rock(1),paper(2): 1
//        The computer is paper.
//        You are rock.
//        You lost
//        The game is over.
//        You total won 1 times
//        Computer total won 3 times

5.39 金融应用:求销售总额

假设你正在某百货商店开始销售工作。你的工资包括基本工资和提成。基本工资是5000美元。使用下面的方案确定你的提成率。
销售额 提成率
0.01~5000美元 8%
5000.01~10000美元 10%
10000.01美元及以上 12%
你的目标是一年挣30000美元。编写程序找出为挣到30000美元,你所必须完成的最小销售额。

public class test {
    public static void main(String[] args){
        final int BASE_SALARY = 5000;
        int salesAmount = 10000;
        double mySalary;
        do{
            mySalary = BASE_SALARY + 5000 * 0.08 + 5000 * 0.10 +  (salesAmount-10000) * 0.12;
            salesAmount++;
        } while (mySalary < 30000);

        System.out.printf("The minimum sales you have to generate is %d", salesAmount);
    }
}

// The minimum sales you have to generate is 210835

5.42 金融应用:求销售额

如下重写编程练习题5.39:
使用for循环替代do-while循环。
允许用户自己输入COMMISSION_SOUGHT而不是将它固定为一个常量。

import java.util.Scanner;

public class test {
    public static void main(String[] args){
        final double COMMISSION_SOUGHT;
        int salesAmount = 10000;
        double mySalary = 0;

        System.out.print("Enter your base salary:");
        Scanner inputScanner = new Scanner(System.in);
        COMMISSION_SOUGHT = inputScanner.nextDouble();


        for(;mySalary < 30000;salesAmount++){
            mySalary = COMMISSION_SOUGHT + 5000 * 0.08 + 5000 * 0.10 +  (salesAmount-10000) * 0.12;
        }

        System.out.printf("The minimum sales you have to generate is %d", salesAmount);

        inputScanner.close();
    }
}

//Enter your base salary:6666
//The minimum sales you have to generate is 196951

趁早上清醒再多画两道~02131035

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值