2019最新《Java详细学习教程》

package com.hello;

import java.lang.invoke.SwitchPoint;
import java.nio.Buffer;
import java.util.DuplicateFormatFlagsException;
import java.util.Scanner;
public class work2 {
  public static void main(String[] args){
  Scanner input= new Scanner(System.in);
      System.out.print("请输入消费金额:");
      int money = input.nextInt();             //用money接受控制台输入的数据
      System.out.println("是否参加优惠购活动:");
      System.out.println("1.满50元,加2元换购百事可乐饮料一瓶");
      System.out.println("2.满100元,加3元换购500ml可乐一瓶");
      System.out.println("3.满100元,加10元换购5公斤面粉");
      System.out.println("4.满200元,加10元可换购1个尼泊尔炒菜锅");
      System.out.println("5.满200元,加20元可换购欧莱雅爽肤水一瓶");
    System.out.print("请选择:");
    int s = input.nextInt();               // 客户选择的换购
      switch (s) { 
      case 1:                                              //客户选择1,
               if (money<50){                        //判断是否满足50元以上,如果小于50元,输出你不满足50元。
                   System.out.println("你不满50元");     
               }else {                                    //否则就是满足50元以上的可以选择1
                
               System.out.println("本次消费总金额:"+(money+2));
              System.out.println("成功换购:1瓶百事可乐"); 
            }
        break;
      case 2:
          if (money<100){
               System.out.println("你不满100元");
           }else {
            
           System.out.println("本次消费总金额:"+(money+3));
          System.out.println("成功换购:500ml可乐1瓶");       
        }
          break ;
      case 3: 
          if (money<100){
               System.out.println("你不满100元");
           }else {
            
           System.out.println("本次消费总金额:"+(money+10));
          System.out.println("成功换购:5公斤面粉"); 
        }
          break ;
      case 4:
          
          if (money<200){
               System.out.println("你不满200元");
           }else {
            
           System.out.println("本次消费总金额:"+(money+10));
          System.out.println("成功换购:1个尼泊尔炒菜锅"); 
        }
          break;
      case 5:
          if (money<200){
               System.out.println("你不满200元");
           }else {
            
           System.out.println("本次消费总金额:"+(money+20));
          System.out.println("成功换购:1瓶欧莱雅爽肤水"); 
        }
          break;
    default:
        break;
    }
}
  public class MyThreadTest {
    private final static Semaphore semaphore = new Semaphore(2);// 设置2个车位
 
    public static void main(String[] args) {
        System.out.println("start");
 
        p(semaphore, true, 1);
        p(semaphore, false, 2);
        p(semaphore, false, 3);
        p(semaphore, true, 4);
        p(semaphore, true, 5);
 
        System.out.println("end");
    }
 
    /**
     * 停车
     *
     * @param semaphore 信号对象
     * @param enterInto 停车true/出库false
     * @param theCarNum 车辆序号
     */
    private static void p(Semaphore semaphore, boolean enterInto, int theCarNum) {
        if (!enterInto) {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("车辆出库");
 
            // 释放1个车位
            // 通过LockSupport.unpark(s.thread)来释放锁,详见AbstractOwnableSynchronizer.unparkSuccessor
            semaphore.release(1);
        }
        try {
            // 如果达到设定的信号量,通过LockSupport.park(this)来释放锁,详见AbstractOwnableSynchronizer.parkAndCheckInterrupt
            semaphore.acquire();
            System.out.println("第 " + theCarNum + " 辆车进入");
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    /**
     *     Semaphore中Sync继承了AbstractQueuedSynchronizer
     *     改变AbstractOwnableSynchronizer中state值(该值记录着剩余信号量)
     *
     *     AbstractOwnableSynchronizer加载时会调用静态代码块获取state的偏移地址:
     *     stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
     *     上述获取对象某个变量的效率比使用反射获取的效率高
     *
     *     protected final boolean compareAndSetState(int expect, int update) {
     *          // stateOffset为state变量的偏移地址
     *         return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
     *     }
     */
 
}/**
     * post请求(用于请求json格式的参数)
     *
     * @param url    地址
     * @param params json格式的参数
     * @return
     */
    public static String doPost(String url, String params) throws Exception {
 
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost( url );// 创建httpPost
        httpPost.setHeader( "Accept", "application/json" );
        httpPost.setHeader( "Content-Type", "application/json" );
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity( params, charSet );
        httpPost.setEntity( entity );
        CloseableHttpResponse response = null;
 
        try {
 
            response = httpclient.execute( httpPost );
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString( responseEntity );
                return jsonString;
            } else {
                logger.error( "请求返回:" + state + "(" + url + ")" );
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
/**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params) {
 
        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI( new URI( url ) );
 
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf( params.get( name ) );
                nvps.add( new BasicNameValuePair( name, value ) );
 
                //System.out.println(name +"-"+value);
            }
            request.setEntity( new UrlEncodedFormEntity( nvps, HTTP.UTF_8 ) );
 
            HttpResponse response = client.execute( request );
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                in = new BufferedReader( new InputStreamReader( response.getEntity()
                        .getContent(), "utf-8" ) );
                StringBuffer sb = new StringBuffer( "" );
                String line = "";
                String NL = System.getProperty( "line.separator" );
                while ((line = in.readLine()) != null) {
                    sb.append( line + NL );
                }
                in.close();
 
                return sb.toString();
            } else {    //
                System.out.println( "状态码:" + code );
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
   /**
     * get请求
     *
     * @return
     */
    public static String doGet(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet( url );
            HttpResponse response = client.execute( request );
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString( response.getEntity() );
                return strResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return null;
    }

smtpserver  = 'smtp.163.com'         # smtp服务器
username    = '[email protected]'    # 发件邮箱账号
password    = '888888888'            # 邮箱登录密码
sender      = '[email protected]'    # 发件人
addressee   = '[email protected]'     # 收件人
exit_count  = 5                      # 尝试联网次数
path        = os.getcwd()            #获取图片保存路径 

注:很多邮箱为了安全起见,不会使用真实的登录密码,而是要使用授权码,在QQ邮箱的设置里面可以找到生成授权码选项。

06 实现拍照

def getPicture():
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    cv2.imwrite(path+'/person.jpg', frame)
    # 关闭摄像头
    cap.release()

07 构造邮件内容

def setMsg():
    # 下面依次为邮件类型,主题,发件人和收件人。
    msg = MIMEMultipart('mixed')
    msg['Subject'] = '电脑已经启动'
    msg['From'] = '[email protected] <[email protected]>'
    msg['To'] = addressee

    # 下面为邮件的正文
    text = "主人,你的电脑已经开机!
照片如下!"
    text_plain = MIMEText(text, 'plain', 'utf-8')
    msg.attach(text_plain)

    # 构造图片链接
    sendimagefile = open(path+'/person.jpg', 'rb').read()
    image = MIMEImage(sendimagefile)
    # 下面一句将收件人看到的附件照片名称改为people.png。
    image["Content-Disposition"] = 'attachment; filename="people.png"'
    msg.attach(image)
    return msg.as_string()

08 实现邮件发送

def sendEmail(msg):
    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, addressee, msg)
    smtp.quit()

09 判断网络联通状态

判断网络联通状态的方法很多,我采用很简单很直接的ping。

# 判断网络是否联通,成功返回0,不成功返回1
# linux中ping命令不会自动停止,需要加入参数 -c 4,表示在发送指定数目的包后停止。
def isLink():
    return os.system('ping -c 4 www.baidu.com')
    # return os.system('ping www.baidu.com')         

10 主函数逻辑

如果网络连接正常,则拍照发邮件。 
如果网络未连接,等待十秒钟再次测试,如果等待次数超过设置的最大次数,程序退出。

def main():
    reconnect_times = 0
    while isLink():
        time.sleep(10)
        reconnect_times += 1
        if reconnect_times == exit_count:
            sys.exit()

    getPicture()
    msg = setMsg()
    sendEmail(msg)

猜你喜欢

转载自blog.csdn.net/dqyxw520/article/details/89790232
今日推荐