- 1
- 2
- 3
- 4
- 5
public Double toDouble(String str){
if ((str==null)||(str.equals(""))) str = "0.0";
if ((str.contains(","))&&(!str.contains("."))) str = str.replace(",", ".");
return new Double(str);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+75
public Double toDouble(String str){
if ((str==null)||(str.equals(""))) str = "0.0";
if ((str.contains(","))&&(!str.contains("."))) str = str.replace(",", ".");
return new Double(str);
}
Лишняя защита никогда не бывает лишней
+75
public class ExtractSubstrings {
public static void main(String[] args) {
String text = “To be or not to be”;
int count = 0;
char separator = ‘ ‘;
int index = 0;
do {
++count;
++index;
index = text.indexOf(separator, index);
} while (index != -1);
String[] subStr = new String[count];
index = 0;
int endIndex = 0;
for(int i = 0; i < count; ++i) {
endIndex = text.indexOf(separator,index);
if(endIndex == -1) {
subStr[i] = text.substring(index);
} else {
subStr[i] = text.substring(index, endIndex);
}
index = endIndex + 1;
}
for(String s : subStr) {
System.out.println(s);
}
}
}
Очень чёткий, простой и с первого взгляда сразу понятный способ сделатЬ сплит строки.
+75
echo( TRUE ? "1" : TRUE ? "2":"3");
//2
http://ideone.com/UBg3T2
В ответ на это:
http://govnokod.ru/12268#comment163978
+75
Long value = Long.valueOf(String.valueOf(avpValue));
не специалист по жабе, но пахнет: сначала по всему коду нагородить огородов с Byte/Short/Integer/Long что бы потом в самом важном месте вот так в лоб все в Long конвертить...
+75
procedure TForm1.RunCode(Code:String;A,B:Cardinal);
var
i,j:Cardinal;
dpth:Word;
itrCounter:Integer;
ans:Integer;
begin
i:=A-1;
repeat
i:=i+1;
if Code[i]='>' then
if p=30000 then p:=1 else p:=p+1;
if Code[i]='<' then
if p=1 then p:=30000 else p:=p-1;
if Code[i]='+' then allspace[p]:=allspace[p]+1;
if Code[i]='-' then allspace[p]:=allspace[p]-1;
if Code[i]='.' then Memo2.Lines.Text:=Memo2.Lines.Text + Chr(allspace[p]);
if Code[i]='[' then
begin
dpth:=0;
j:=i;
repeat
if (Code[j]=']') and (dpth>0) then dpth:=dpth-1;
j:=j+1;
if Code[j]='[' then dpth:=dpth+1;
if j>B then
begin
ShowMessage('Обнаружен незакрытый цикл. Выполнение остановится');
running:=False;
Exit;
end;
until (Code[j]=']') and (dpth=0);
itrCounter:=0;
while allspace[p]<>0 Do
begin
if running=False then Exit;
RunCode(Memo1.Text,i+1,j-1);
itrCounter:=itrCounter+1;
if itrCounter=10000000 then
begin
ans:=MessageDlg('Выполнение программы вероятно зациклилось (прошло уже 10 000 000 итераций). Возможно код содержит ошибки.' + #13 + 'Остановить выполнение?',mtConfirmation,[mbYes,mbNo],0);
if ans=mrYes then running:=False;
if ans=mrNo then itrCounter:=0;
end;
end;
i:=j;
end;
if Code[i]=',' then EnterChar;
Application.ProcessMessages;
until (i>=B) or (running=False);
end;
Процедура интерпретации brainfuck кода
+75
public class Тетрадка {
public static РабочийДень закрытьДень(РабочийДень последний, double зарплатаВыдана, double кассуЗабрали) {
последний.выдана_зп = зарплатаВыдана;
последний.выручку_забрали = кассуЗабрали;
РабочийДень новый = new РабочийДень();
Calendar c = Calendar.getInstance();
новый.год = c.get(Calendar.YEAR);
новый.месяц = c.get(Calendar.MONTH);
новый.день = c.get(Calendar.DAY_OF_MONTH);
последний.следующийДень = новый.год + "-" + новый.месяц + "-" + новый.день;
новый.предыдущийДень = последний.год + "-" + последний.месяц + "-" + последний.день;
новый.остаток = последний.остаток.сделатьКопию();
новый.вкассе = последний.вкассеОбщее - последний.выручку_забрали;
новый.общаяЗарплатаПрошлогоДня = последний.общаяЗарплата - последний.выдана_зп;
String папка = "./days/" + новый.предыдущийДень + "/" + новый.предыдущийДень + "-";
последний.сохранить(папка + "РабочийДень.data", папка + "ОстатокКарт.data", папка + "Приход.data");
новый.сохранить("./последнийРабочийДень.data", "./последнийОстатокКарт.data", "./последнийПриход.data");
return новый;
}
....
Brainexplode
+75
v.getParent().getParent().getParent().getParent().requestDisallowInterceptTouchEvent(true);
Не моё, но не могу не поделиться :)
+75
Process process = Runtime.getRuntime().exec("su");
OutputStream outputStream = process.getOutputStream();
String cmd = "keycode " + KeyEvent.KEYCODE_BACK;
outputStream.write((cmd + "\n").getBytes("ASCII"));
Андроид. Вот такой вот прекрасный способ программно нажать кнопочку "Back".
http://stackoverflow.com/questions/5832861/android-back-key-by-software
+75
@Override
public boolean onTouchEvent(MotionEvent e) {
x=(int)e.getX(); y=(int)e.getY();
/* ... */
synchronized(this) {
try {this.wait(1000);}
catch (InterruptedException ex) {}
}
return true;
}
/* Gets (screen/pixel) x,y coordinates of last touch event*/
public boolean GetCoordinates(MutablePoint coordinates) {
if (x==-1) return false;
coordinates.init(x,y);
return true;
}
https://github.com/acl33/AndroidDasher/blob/master/src/dasher/android/DasherCanvas.java
+75
private void viewField(int id) {
try {
List<Fieldmaterials> materials = materialsSession.FieldmaterialsBy(id);
int size = materials.size() - 1;
int i = 0;
JSONWriter json = new JSONStringer().object();
json.key("namefield").array();
while (i <= size) {
Fieldmaterials get = materials.get(i);
json.value(get.getNamefield());
i++;
}
json.endArray();
json.key("typefield").array();
i = 0;
while (i <= size) {
Fieldmaterials get = materials.get(i);
json.value(get.getTypefield());
i++;
}
json.endArray();
json.key("orderfield").array();
i = 0;
while (i <= size) {
Fieldmaterials get = materials.get(i);
json.value(get.getOrderfieldmaterials());
i++;
}
json.endArray().endObject();
} catch (Exception e) {
e.printStackTrace();
}
Не нашел более хорошего способа сериализовать в JSON. Нужно было оформить поля объектов в массивы, что-бы потом удобно разобрать в javascript