class MemberIDException extends Exception{
public MemberIDException(String mID){
super("ERROR: " + mID)
}
public void contactWith(){ // 自訂例外中的自訂方法
System.out.println("Please try again.");
}
}
public static void main(String[] args){
try{
checkMemberID("123456");
}
catch(MemberIDException e){
tem.out.println(e.getMessage());
e.contactWith(); // 自訂例外類別中的自訂方法
}
}
public static void checkMemberID(String mID) throws MemberIDException{
if(mID.length() != 5){
throw new MemberIDException(mID); // 自訂例外
}
}
轉載自http://jhengjyun.blogspot.tw/2010/06/java-extends.html
2017/12/16
Java 自訂例外處理
2017/12/07
Servlet使用外部API
/*
參考資料
http://bit.ly/2umBcG8
*/
/*
用Servlet POST 給API.AI請求與取得回應,正常版不亂碼
*/
package jt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
public class AIConversationServlet extends HttpServlet {
private String tokenId = "";//API.AI那邊的TokenId
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userInput = new String(request.getParameter("userInput").getBytes("UTF-8"));
String url = "https://api.api.ai/v1/query?v=20150910";
url = this.stringParser(url);
String urlParameters = "{\"query\": [\"" + userInput + "\"],\"lang\": \"zh-cn\",\"sessionId\": \"1234567890\"}";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json;charset=utf-8");
post.setHeader("Authorization", tokenId);
post.setEntity(new StringEntity(urlParameters, "UTF-8"));
HttpResponse theResponse = httpClient.execute(post);
HttpEntity entity = theResponse.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
out.write(responseString);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public String stringParser(String url) throws IOException {
String url2 = new String();
for (int j = 0; j < url.length(); j++) {
if (url.substring(j, j + 1).matches("[\\u4e00-\\u9fa5]+")) {
try {
url2 = url2 + URLEncoder.encode(url.substring(j, j + 1), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
url2 = url2 + url.substring(j, j + 1).toString();
}
}
return url2;
}
public static String getBody(HttpServletRequest request) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}
}
需匯入apache的套件
2017/12/04
Servlet輸出不亂碼
程式如下
如果是GET,要先把在網址列取得的參數用getBytes取得並轉成UTF-8,之後才輸出。可以上方的程式碼。
最近又發生亂碼的情況了,看來還有別的會亂碼的情況我沒注意到
就是我從jsp送post請求給servlet,servlet再把這個從jsp送來的參數顯示到另一個jsp
我在servlet用System.out.println()查看這個參數,才發現進到servlet時就亂碼了,所以應該不是jsp的問題
後來我在servlet的doPost的第二行加入request.setCharacterEncoding("UTF-8");
就解決了
原本以為
package newpackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userInput = new String(request.getParameter("userInput").getBytes("UTF-8"));
out.print(userInput);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("哈囉");
}
}
不管是POST還是GET第一行都要先放response.setContentType("text/html;charset=UTF-8");這行如果是GET,要先把在網址列取得的參數用getBytes取得並轉成UTF-8,之後才輸出。可以上方的程式碼。
最近又發生亂碼的情況了,看來還有別的會亂碼的情況我沒注意到
就是我從jsp送post請求給servlet,servlet再把這個從jsp送來的參數顯示到另一個jsp
我在servlet用System.out.println()查看這個參數,才發現進到servlet時就亂碼了,所以應該不是jsp的問題
後來我在servlet的doPost的第二行加入request.setCharacterEncoding("UTF-8");
就解決了
原本以為
2017/11/29
解決Ubuntu不能更新oh-my-zsh的問題
有時Ubuntu Server上他會問你是否更新Oh My Zsh,如下:
[Oh My Zsh] Would you like to check for updates? [Y/n]: y
Updating Oh My Zsh
error: Cannot pull with rebase: You have unstaged changes.
There was an error updating. Try again later?
按y發現他不給更新
記得設定git的信箱和名稱
2017/11/28
2017/10/01
mac MQTT(mosquitto)安裝
請先安裝Homebrew,要用Homebrew安裝mosquitto
安裝mosquitto
$ brew intall mosquitto
我安裝過程有出現一些Error訊息,所以安裝完後又把mosquitto刪掉,相依的套件也跟著刪掉再重新安裝一次。
Homebrew會裝在/usr/local/Cellar/mosquitto這個位置
把mosquitto加入.zshrc環境變數,這樣才可以在全域下指令操作它
打開.zshrc
$ vi .zshrc
在上面加入這行
export PATH=/usr/local/Cellar/mosquitto/1.4.14_1/sbin:$PATH
馬上讓.zshrc生效
$ source .zshrc
用brew啟動mosquitto服務
$ brew services start mosquitto
用brew停止mosquitto服務
$ brew services stop mosquitto
用brew重啟mosquitto服務
$ brew services restart mosquitto
用NodeMCU adc讀取ACS712訊號並轉換電壓電流
使用的是NodeMCU v3
ACS712(30A)
使用NodeMCU上的adc來讀取ACS712的類比訊號,直接使用NodeMCU上的VU腳位來供給ACS712 5V的電,輸出的訊號電壓準位為5V,使用2.4k歐姆與4.7k歐姆來降為3.3V,然後接回adc腳位
來源
這是加了判斷電器是否開啟,並根據條件發送通知的小改版本 以吹風機為例,一打開就發送通知。
來源
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid, passwd)
wifi.sta.connect()
wifi.sleeptype(wifi.NONE_SLEEP)
local refreshInterval = .2
local mVperAmp = 100 --100mV on 1A
local Voltage = 0
local VRMS = 0
local AmpsRMS = 0
local maxErr = 0
local avgErr = 0
local totalMeasurement = 0
local TotalPwr = 0
tmr.alarm(0, refreshInterval*1000, tmr.ALARM_SEMI, function()
totalMeasurement = totalMeasurement + 1
Voltage = getVPP()
VRMS = (Voltage/2.0) * 0.707
AmpsRMS = (VRMS * 1000) / mVperAmp
Pwr = AmpsRMS * 220 /10
TotalPwr = TotalPwr + Pwr
print(totalMeasurement..". AvrPwr: "..string.format("%.2f",TotalPwr * 10/totalMeasurement).."W - "..string.format("%.2f",AmpsRMS).."A - "..string.format("%.2f",Pwr * 10).."W")
print(" ")
tmr.start(0)
end)
function getVPP()
local result = 0
local readValue = 0
local maxValue = 0
local minValue = 1024
local nbrReadings = 0
while (nbrReadings<1000 do="" if="" readvalue=""> maxValue) then
maxValue = readValue
elseif (readValue < minValue) then
minValue = readValue
end
nbrReadings = nbrReadings + 1
end
print(totalMeasurement..". Max: "..maxValue.." - Min: "..minValue)
result = (math.abs(maxValue - minValue - 6) * 5)/1024
if (maxValue - minValue > maxErr) then
maxErr = maxValue - minValue
end
avgErr = avgErr + (maxValue - minValue) / 10
print(totalMeasurement..". Err: "..maxValue - minValue.." maxErr: "..maxErr.. " AvgErr: "..string.format("%.2f", avgErr * 10/totalMeasurement))
return result
end
1000>這是加了判斷電器是否開啟,並根據條件發送通知的小改版本 以吹風機為例,一打開就發送通知。
local refreshInterval = 2
local mVperAmp = 66 --66mV on 1A
local Voltage = 0
local VRMS = 0
local AmpsRMS = 0
local maxErr = 0
local avgErr = 0
local totalMeasurement = 0
local TotalPwr = 0
airConditionerStatus = false
sendStatus = false
tmr.alarm(0, refreshInterval*1000, tmr.ALARM_AUTO, function()
totalMeasurement = totalMeasurement + 1
Voltage = getVPP()
VRMS = (Voltage/2.0) * 0.707
AmpsRMS = (VRMS * 1000) / mVperAmp
if AmpsRMS>3 then
airConditionerStatus = true
while airConditionerStatus do
if airConditionerStatus and sendStatus~=true then
sendHttpRequest()
sendStatus = true
print(airConditionerStatus)
else break
end
end
else
airConditionerStatus = false
sendStatus = false
end
Pwr = AmpsRMS * 220 /10
TotalPwr = TotalPwr + Pwr
print(totalMeasurement..". AvrPwr: "..string.format("%.2f",TotalPwr * 10/totalMeasurement).."W - "..string.format("%.2f",AmpsRMS).."A - "..string.format("%.2f",Pwr * 10).."W")
print(" ")
end)
function sendHttpRequest()
http.post("http://192.168.11.5:8101/ESP8266/Service",
"Content-Type: application/json\r\n",
"{\"Power\":\"on\"}",
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
--http://httpbin.org/ip
end
function getVPP()
local result = 0
local readValue = 0
local maxValue = 0
local minValue = 1024
local nbrReadings = 0
while (nbrReadings<1000) do
readValue = adc.read(0)
if (readValue > maxValue) then
maxValue = readValue
elseif (readValue < minValue) then
minValue = readValue
end
nbrReadings = nbrReadings + 1
end
print(totalMeasurement..". Max: "..maxValue.." - Min: "..minValue)
result = (math.abs(maxValue - minValue - 6) * 5)/1024
if (maxValue - minValue > maxErr) then
maxErr = maxValue - minValue
end
avgErr = avgErr + (maxValue - minValue) / 10
print(totalMeasurement..". Err: "..maxValue - minValue.." maxErr: "..maxErr.. " AvgErr: "..string.format("%.2f", avgErr * 10/totalMeasurement))
return result
end
--http://bit.ly/2x4yyFR
2017/09/16
在mac上安裝lua
直接搜尋lua去官網下載最新的安裝檔lua-5.3.4.tar.gz
把lua-5.3.4.tar.gz放到家目錄,並解壓縮
$ cd lua-5.3.4
這裡我不知在做啥,測試?
$ make macosx test
這才是安裝,沒打sudo他會有/usr/local/man/man1: Permission denied的訊息,所以要加 sudo
$ sudo make macosx install
測試是否安裝成功
$ lua
Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio
>
2017/09/13
在MacOS上燒錄ESP8266 NodeMCU韌體
之前都是在Windows上燒,沒想到在Mac上燒沒那麼容易...
因為Windows有NodeMCU Flasher這套軟體,Mac上似乎沒有...因此增加燒錄的困難
2017/08/27
OM2M
IN-CSE和MN-CSE的啟動方式一樣。
org.eclipse.om2m.remoteCseName
org.eclipse.om2m.remoteCseAddress
org.eclipse.om2m.remoteCsePort
org.eclipse.om2m.remoteCseContext
IN-CSE要啟動,MN-CSE才能啟動,否則MN-CSE每10秒會檢查一次 IN-CSE是否有啟動。
很像要在
如果要把MN-CSE設定成也可以讓IN-CSE管理,必須去MN-CSE的config.ini設定,很像要設定五個參數 為:
org.eclipse.om2m.remoteCseIdorg.eclipse.om2m.remoteCseName
org.eclipse.om2m.remoteCseAddress
org.eclipse.om2m.remoteCsePort
org.eclipse.om2m.remoteCseContext
config.ini的位置在/Users/....../git/org.eclipse.om2m/org.eclipse.om2m.site.mn-cse/target/products/mn-cse/macosx/cocoa/x86_64/configuration
IN-CSE也有一個config.ini,與MN-CSE一樣的目錄結構
/Users/xanxus/git/org.eclipse.om2m/org.eclipse.om2m.site.in-cse/target/products/in-cse/macosx/cocoa/x86_64/configuration
2017/08/26
設定Raspberry Pi靜態IP
有時候Pi的IP會隨意變動,因為Router會隨機分配IP?這次用192.168.0.110,下次就變192.168.0.111,這樣要SSH或VNC連線會很不方便,還要再查Pi的IP, 故這裡就是說如何讓他每次配的IP讓他固定。
2017/08/11
Docker基本指令與操作
在這記錄一些過程及相關指令
先去Docker Hub把別人做好的Tomcat映像檔pull下來
這裡我是直接搜尋Tomcat點第一個到這個
網址
我挑8.5.20-jre8
pull下來:
~ docker pull tomcat:8.5.20-jre8
2017/07/25
Raspberry Pi 3 Model B..........
當時要燒Ubuntu進去遇到的一些問題...
根據這頁面http://bit.ly/2uRZUC0的這個指令:
橘色那個...
$ sudo dd if=~/Downloads/<image file> of=<drive address> bs=32MB
不能run...
換成這樣就可以了:
$ sudo dd if=/Users/xanxus/Downloads/ubuntu-core-16-pi3.img of=/dev/disk2 bs=32m
後面改成小寫,且只有m
2017/07/18
2017/07/11
Node-RED
啟動Node-RED
$ node-red
http://127.0.0.1:1880/ 就是Node-RED平台的網址
$ node-red
11 Jul 20:39:32 - [info] Welcome to Node-RED =================== 11 Jul 20:39:32 - [info] Node-RED version: v0.16.2 11 Jul 20:39:32 - [info] Node.js version: v6.11.0 11 Jul 20:39:32 - [info] Darwin 16.6.0 x64 LE 11 Jul 20:39:33 - [info] Loading palette nodes 11 Jul 20:39:33 - [warn] ------------------------------------------------------ 11 Jul 20:39:33 - [warn] [rpi-gpio] Info : Ignoring Raspberry Pi specific node 11 Jul 20:39:33 - [warn] ------------------------------------------------------ 11 Jul 20:39:33 - [info] Settings file : /Users/xanxus/.node-red/settings.js 11 Jul 20:39:33 - [info] User directory : /Users/xanxus/.node-red 11 Jul 20:39:33 - [info] Flows file : /Users/xanxus/.node-red/flows_XanxusMacde-MacBook-Pro.local.json 11 Jul 20:39:33 - [info] Server now running at http://127.0.0.1:1880/ 11 Jul 20:39:33 - [info] Starting flows 11 Jul 20:39:33 - [info] Started flows
http://127.0.0.1:1880/ 就是Node-RED平台的網址
2017/07/06
2017/07/05
API.AI
自己用curl下get請求的寫法範例:
curl "https://api.api.ai/v1/query?v=20150910&query=%e6%88%91%e6%83%b3%e5%8e%bb%e9%a6%99%e7%b1%b3%e6%b9%af%e6%b9%af&lang=zh-CN&sessionId=1234567890" -H "Authorization:Bearer 2b0ed04782064644b8066768bbda2fa5" -H "Content-Type: application/json; charset=utf-8"
2017/06/23
安裝TensorFlow
主要有以下幾種安裝方法:
- virtualenv
- "native" pip
- Docker
- installing from sources, which is for experts and is documented in a separate guide.
官方推薦用第一種,那時第一次裝沒看仔細竟然第一到第三種方式都用了...
安裝SublimeREPL...Sublime上寫python好用的套件
SublimeREPL套件是解決在Sublime上不支援使用者輸入文字的套件,裝了這個套件就可以讀取輸入的字串,就像使用終端機用python一樣。
安裝Python3
直接brew安裝
$ brew install python3
查看python版本確認安裝
$ python3 --version
安裝python3 也會幫你把pip3裝好
查看pip3版本
$pip3 --version
用pip3查看已經安裝的套件
$pip3 list
更新pip3
$ pip3 install -U pip
直接在終端機使用直譯器(⌃+d離開此模式)
➜ ~ python3
Python 3.6.1 (default, Apr 4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello")
Hello
>>>
執行.py檔案,先到.py檔案的地方
➜ ~ cd Desktop
➜ Desktop ls
python測試.py
➜ Desktop python3 python測試.py
Xanxus
$ brew install python3
查看python版本確認安裝
$ python3 --version
安裝python3 也會幫你把pip3裝好
查看pip3版本
$pip3 --version
用pip3查看已經安裝的套件
$pip3 list
更新pip3
$ pip3 install -U pip
直接在終端機使用直譯器(⌃+d離開此模式)
➜ ~ python3
Python 3.6.1 (default, Apr 4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello")
Hello
>>>
執行.py檔案,先到.py檔案的地方
➜ ~ cd Desktop
➜ Desktop ls
python測試.py
➜ Desktop python3 python測試.py
Xanxus
2017/06/19
2017/06/18
2017/06/14
Excel矩陣相乘操作
本篇以官方提供的範例,來操作Excel的矩陣相乘,以文字說明操作流程,影片輔助。
官網MMULT 函數操作說明 http://bit.ly/2rgXAPO
- 一開始從影片可以看到,先在右下區域選四個格子
- 再把公式貼到函數格
- 按下Ctrl+Shift+Enter
- 完成
2017/06/09
2017/06/06
2017/05/09
Servlet 安裝 JSTL Library 筆記
先到Apache Taglibs
點最新的[Standard]
一樣可以點最新的download
會看到下面有四個分別為:
Impl
Spec
EL
Compat
都載下來
全部都匯入到要用的WebApplication
點最新的[Standard]
一樣可以點最新的download
會看到下面有四個分別為:
Impl
Spec
EL
Compat
都載下來
全部都匯入到要用的WebApplication
這樣就完成了,一開始不知道,只挑一個,結果不能用,因為四個每個都有作用。
因為這樣搞了蠻久,因此還是在這記錄一下...
2017/05/08
2017/04/16
2017/04/15
在Java專案創造專門放jar的資料夾
有時我們需要把外部的jar檔加入到Java Application中,之前是直接找電腦中jar檔的位置,直接加入,但如果jar檔不小心砍掉了,變成Java Application有用到那個jar的method都會不能用,因為你砍掉了麻!
這篇就是說如何把你剛下載的jar檔案,再複製一份放到Java Application中,這樣jar就跟著專案走了!
環境資訊:
NetBeans 8.2
MacOS Sierra 10.12.4
2017/04/09
2017/04/02
2017/03/29
NetBeans開發Java EE發生Deployment error: Starting of Tomcat failed. See the server log for details...因素
因常遇到Netbeans在mac上跑Tomcat常常會出現這個錯誤,但原因到現在我還不明,但今天爬到一篇關掉Proxy就可以run了,這次是唯一一次關掉它就可run,過去都要開機等一段時間,不然就是Tomcat已經啟動了,有看到Tomcat歡迎畫面,但NetBeans還在啟動卡死狀態,不代表每次關掉都可以解決。
10038 - Jolly Jumpers
/*
482 - Permutation Arrays http://bit.ly/2o2i80g
10038 - Jolly Jumpers http://bit.ly/2mMH3Fn
*/
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int N=4;
while (cin>>N){
int s[3001],check[3001]={0};
bool ok=1;
cin>>s[0];
for (int i=1 ; i<N ; i++) {
cin>>s[i];
int temp = abs(s[i]-s[i-1]);
if (temp <= 3000) {
check[temp] = check[temp] +1;
}
}
for (int i=1;i<N;i++){
cout<<check[i];//0120,check[0]=0,check[1]=0,check[2]=1,check[3]=2,check[4]=0
if (check[i]==0) {
ok = 0;
break;
}
//cout<<check[i];//i從0開始到N,印出0111
}
if (ok) cout<<"Jolly\n";
else cout<<"Not jolly\n";
}//while結尾
return 0;
}
題目網址:http://bit.ly/2mMH3Fn這題不難,只是要知道切入點。
設輸入測資為4 1 4 2 3,輸出Jolly
第一個for迴圈做的事是,找到相鄰兩數的絕對值,並把絕對值當索引,並且+1
1、4的絕對值是3
4、2的絕對值是2
2、3的絕對值是1
每次把它們放到temp暫存,且必定小於3000,
最後check[3]、check[2]、check[1]的值都等於1
第二個for迴圈,走訪check[1~N-1],只要其中一個值是0,就是Not jolly
很顯然,check[1~4-1]沒有一個是0,所以印出Jolly
歸納一些解題想法:
1.需仔細觀察會Jolly和Not jolly與測資的情況。
2.藉由測資特性去思考,通常會Jolly的,每個相鄰兩數的絕對值,一定是有順序性且不重複,藉由這特性把絕對值當索引,存入一次記錄為1。而Not jolly,通常絕對值會跳很大,或都相等,如1 3 5 7,會變成每次都把同一個索引+1,其他索引都是0,必定就產生0,就一定是Not jolly。
2017/03/21
10420:List of Conquests
//http://bit.ly/2nzLF1m
#include <iostream>
#include <map>
using namespace std;
int main() {
int n;
map<string, int> record;
map<string, int>::iterator i;
while (cin>>n && n!=1) {
string country, tmp;
while (n--) {
cin >> country;
record[country]++;
getline(cin, tmp);
}
for ( i = record.begin(); i != record.end(); i++)
cout << i->first << " " << i->second << endl;
}
return 0;
}
題目網址:http://bit.ly/2nzLF1m
2017/03/19
10101 - Bangla Numbers
#include<iostream>
using namespace std;
void printNumber( long long n ){
if( n == 0 ) return;
if( n/10000000 ){
printNumber( n/10000000 );
cout<<" kuti";
n %= 10000000;
}
if( n/100000 ){
printNumber( n/100000 );
cout<<" lakh";
n %= 100000;
}
if( n/1000 ){
printNumber( n/1000 );
cout<<" hajar";
n %= 1000;
}
if( n/100 ){ //764
printNumber( n/100 );
cout<<" shata";
n %= 100;
}
if( n ) cout<<" "<<n;
}
int main(){
long long n;
int serialNumber = 1;//serialNumber是每筆測試資料的編號
while(cin >> n && n != 0){
cout<<serialNumber<<".";
if( n ) printNumber( n );
serialNumber++;
}
return 0;
}
上面程式碼原作者在這http://knightzone.org/?p=1789,我稍微修改,功能也完整來追蹤一次,設n=764
第一次在main中printNumber(n)呼叫,先做if( n/100 )的敘述,
第二次在if( n/100 )中的printNumber(n/100)呼叫遞迴,764/100=7,丟進7這參數進去,
最後會執行第30行的if,印出7,這次呼叫完畢。
會回到第一次繼續執行,故印出 shata,接著再執行n %= 100; n計算後為64
再做30行敘述,印出64
而其他同理,因數字大就不追蹤了。
以下是我寫失敗的程式碼:
//http://bit.ly/2nDnxrI
//764 7 shata 64
#include<iostream>
using namespace std;
int howManyPlace(int n){//回傳這個數字有幾位數
int count = 0;
while (n != 0) {
n = n / 10;
count++;
}
return count;
}
int main() {
int serialNumber = 0;
int n = 0;
while (cin >> n && n != 0) {
serialNumber++;
if(howManyPlace(n) == 3){
cout<<serialNumber<<". "<<n/100<<" shata "<<n%100;
}
if(howManyPlace(n) == 5){
int a,b,c;
a = n/1000;
b = (n%1000)/100;
c = n%100;
cout<<serialNumber<<". "<<a<<" hajar "<<b<<" shata "<<c;
}
}
return 0;
}
題目網址:http://bit.ly/2nDnxrI
2017/03/18
10929 - You can say 11
#include<iostream>
using namespace std;
int main(){
int n = 0;
while(cin>>n && n!=0){
if(n%11 == 0){
cout<<n<<" is a multiple of 11.";
}
else{
cout<<n<<" is not a multiple of 11.";
}
}
return 0;
}
題目網址:http://bit.ly/2nyjwYG
10055 - Hashmat the Brave Warrior
#include<iostream>
using namespace std;
int main(){
int firstNumber = 0;
int EndNumber = 0;
while(cin>>firstNumber>>EndNumber){
int temp = 0;
if(firstNumber > EndNumber){
temp=EndNumber;
EndNumber=firstNumber;
firstNumber=temp;
}
cout<<EndNumber-firstNumber;
}
return 0;
}
題目網址:http://bit.ly/2nQ1nS2
11332 - Summing Digits
#include<iostream>
using namespace std;
int main(){
int n;
while( cin>>n && n!=0 ){
while( n/10 ) n = n/10 + n%10;
cout<<n;
}
return 0;
}
假設輸入是47while迴圈第一次n=47,回傳11
while迴圈第二次n=11,回傳2
while迴圈第三次n=2,因2/10,無法除,因此while判定為false,停止迴圈
並且印出2
題目網址:http://bit.ly/2mCUJyr
2017/03/17
11764: Cricket Field
#include <iostream>
using namespace std;
int main() {
int testCase = 0;
cin>>testCase;//輸入有幾筆測試資料
int caseNumber = 0;
while(testCase--){
int wallQuantity = 0;//高牆的數量
int wallHeight = 0;//牆的高度
int wallFirst = 0;//第一個高牆
int highJumps = 0;
int lowJumps = 0;
cin>>wallQuantity;
cin>>wallFirst;
for(int i = 0 ; i<wallQuantity-1 ; i++){
cin>>wallHeight;
if(wallHeight > wallFirst){
highJumps ++;
}
if(wallHeight < wallFirst){
lowJumps ++;
}
wallFirst = wallHeight;
}
caseNumber++;
cout<<"Case "<<caseNumber<<": "<<highJumps<<" "<<lowJumps;
}
return 0;
}
這題的重點是23行,不管有沒有大於或小於,都要走訪到下一個數字,並且取代目前的wallFirst。一開始我是把這行寫在if內,但這樣是錯的題目網址:http://bit.ly/2mAas0n
11192 - Group Reverse
#include <iostream>
using namespace std;
int main() {
int textLength = 0;
while ((cin >> textLength) && (textLength != 0)) {
string word = "";
cin>>word;
int group = word.length() / textLength;
for (int i = 0; i < word.length(); i += group) {
for (int j = i + group - 1; j >= i; j--) {
cout << word[j];
}
}
}
return 0;
}
題目網址 http://bit.ly/2mTqO7Y
補充:
字串翻轉
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
string str1 = "Xanxus";
for(int i = str1.length();i>=0;i--){
cout<<str1[i];
}
return 0;
}
2017/03/13
11364: Parking
#include <iostream>
using namespace std;
int main() {
int testCase; //測資數目
int storeNum; //商店的數量
cin>>testCase;
while (testCase--) {
int minNumber = 9999; //最小值
int maxNumber = 0; //最大值
int number; //商店號碼
cin>>storeNum;
for (int i = 0; i < storeNum; i++) {
cin>>number;
if (number > maxNumber) {
maxNumber = number;
}
if (number < minNumber) {
minNumber = number;
}
}
cout << (maxNumber - minNumber)*2;
}
return 0;
}
UVA題目網址http://bit.ly/2miHPEJ
2017/03/09
10783 - Odd Sum
#include <iostream>
using namespace std;
int main() {
int testCase = 0, a = 0, b = 0,count=0;
cin>>testCase;
while (testCase--) {
int total = 0;
cin >> a>>b;
for (int i = a; i <= b; i++) {
if (i % 2 != 0) {
total += i;
}
}
count++;
cout<<"Case"<<" "<<count<<": "<<total<<"\n";
}
return 0;
}
UVA此題目網址http://bit.ly/2m374Lm
100 - The 3n + 1 problem
#include <iostream>
using namespace std;
int calc_cycle_length(int n) {
int cycle_length = 1;
while (n != 1) {
if (n == 1) {
return false;
} else if (n % 2 != 0) {
n = 3 * n + 1;
} else {
n = n / 2;
}
cycle_length++;
}
return cycle_length;
}
int main() {
int firstNum, endNum;
int temp = 0;
int cycleLength = 0;
int maxLength ;
while (cin >> firstNum >> endNum && (firstNum != 0 || endNum != 0)) {
cout<<firstNum<<" "<<endNum<<" ";
maxLength = 0;
if (firstNum > endNum) {
temp = endNum;
endNum = firstNum;
firstNum = temp;
}
for (int i = firstNum; i < endNum; i++) {
cycleLength = calc_cycle_length(i);
if (cycleLength > maxLength) {
maxLength = cycleLength;
}
}
cout<<maxLength<<"\n";
}
return 0;
}
拿到瘋狂程設run有一筆99999 99999這筆測資出不來,瘋狂程設這筆結果是要輸出227,但我只能輸出0.....
題目網址http://bit.ly/2eOC6q1
2017/03/07
C++ 字串
C++字串本質是由字元所組成的陣列,並在最後加上一空字元'\0'
char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};
它是用空字元來識別一陣列是否為字串
輸出:cout << str << endl;
char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};
它是用空字元來識別一陣列是否為字串
輸出:cout << str << endl;
2017/03/04
在Tomcat部署Servlet
一、創造Servlet程式,檔名HelloWorld.java
// Filename : HelloWorld.java
// Description : This servlet merely says hello!
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Hello, Cruel World!</title></head>");
out.println("<body>");
out.println("<h1>Hello, Cruel World !</h1>");
out.println("This is my first servlet.");
out.println("</body>");
}// end doGet
}///:~
2017/03/03
讓AJAX動態內容支援瀏...的補充註解
為了解決我ajax回上一頁抓的資料不見的問題,而找到的暗黑大的這篇文章,雖然最後用了sessionStorage去解決,但還是把他那篇文章程式碼研究了一下,因此還是想記錄起來。
其實就是同樣的程式碼但我多加了幾行註解。
參考:http://bit.ly/2lJqANm
其實就是同樣的程式碼但我多加了幾行註解。
<!DOCTYPE html>
<html>
<head>
<title>AJAX GoBack</title>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.ba-bbq/1.2.1/jquery.ba-bbq.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#s1").show();
$("input.nav-btn").click(function() {
var $btn = $(this); //this為目前被點擊的btn物件
$btn.parent().hide(); //當點擊按鈕後,就把自己隱藏。如:點擊STEP1的按鈕,就把自己的父類別div隱藏
var nav = $btn.data("nav"); //取得現在這個按鈕的data-nav屬性的值,第一次點擊就取得s2,$btn.data("nav")就是印出s2
$("#" + nav).show(); //顯示下一個div
//將目前的步驟加註在location.hash
$.bbq.pushState({
step: nav
}); //pushState裡面的東西就是key:value形式
});
//hash變化時觸發hashchange事件
$(window).bind('hashchange', function(e) { //控制上一頁的動作
//由hash取出step參數,決定要顯示哪一個div
var s = e.getState("step") || "s1"; //e.getState("step")回傳s2 or s3
//if (!$("#" + s + ":visible").length) {
$("#main > div").hide();
$("#" + s).show();
//}
});
});
</script>
<style>
#main div {
width: 300px;
height: 200px;
display: none;
padding: 10px;
}
#s1 {
background-color: #ff7777;
}
#s2 {
background-color: #77ff77;
}
#s3 {
background-color: #7777ff;
}
</style>
</head>
<body>
<div id="main">
<div id="s1">
STEP1
<input type="button" class="nav-btn" value="Next" data-nav="s2" />
</div>
<div id="s2">
STEP2
<input type="button" class="nav-btn" value="Next" data-nav="s3" />
</div>
<div id="s3">
FINAL
<input type="button" value="Submit" />
</div>
</div>
</body>
</html>
參考:http://bit.ly/2lJqANm
2017/02/25
jQuery
新增DOM元素
<script type="text/javascript">
$(document).ready(function() {
$("<p>123</p>").appendTo("body");
});
</script>
如此可以包裝一個HTML片段,並新增body元素的最後一個子元素
2017/02/22
解決Sublime HTMLPrettify套件的node.js was not found in the default path. pleas....錯誤 mac
附上我的系統環境參考
作業系統:macOS Sierrra 10.12.3
Sublime Text3
Node.js v6.10.0
在我安裝完Node.js,且測試正常可run後 用⌘+⇧+H格式化程式碼時跳出錯誤視窗,上面寫node.js was not found in the default path. please specify the location mac
應該是Sublime抓不到Node.js的路徑
這時請在終端機下這個指令 $ which node /usr/local/opt/nvm/versions/node/v6.10.0/bin/node
我這裡是回應以上路徑
請在他剛剛跳出那個錯誤視窗後,他幫你開啟的HTMLPrettify.sublime-settings檔案改成以下這段
參考
https://my.oschina.net/u/1040928/blog/404391
作業系統:macOS Sierrra 10.12.3
Sublime Text3
Node.js v6.10.0
在我安裝完Node.js,且測試正常可run後 用⌘+⇧+H格式化程式碼時跳出錯誤視窗,上面寫node.js was not found in the default path. please specify the location mac
應該是Sublime抓不到Node.js的路徑
這時請在終端機下這個指令 $ which node /usr/local/opt/nvm/versions/node/v6.10.0/bin/node
我這裡是回應以上路徑
請在他剛剛跳出那個錯誤視窗後,他幫你開啟的HTMLPrettify.sublime-settings檔案改成以下這段
"node_path": {
"windows": "C:/Program Files/nodejs/node.exe",
"linux": "/usr/bin/nodejs",
"osx": "/usr/local/opt/nvm/versions/node/v6.10.0/bin/node"
},
主要是"osx": 裡面的路徑,改成剛剛用$ which node給你的路徑
這樣就可以正常了
參考
https://my.oschina.net/u/1040928/blog/404391
訂閱:
文章 (Atom)


