java programing question - General Questions and Answers

Hi, I am just learning to program in java, i am using eclipse, I just wanted to apply something to what I have been reading, maybe I am getting ahead, but anyways, I wanted to create a program that measures dimmensional weight, you input the lenght, then the widht, and then the hight, take those numbers and multiply them by 250, that will give you the dimmensional weight, this is the code I created for that:
import java.util.Scanner;
class kilos {
static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
double length;
double width;
double height;
double total;
System.out.print("Lenght");
length=myScanner.nextDouble();
System.out.print("width");
width=myScanner.nextDouble();
System.out.print("height");
height=myScanner.nextDouble();
System.out.print("dimmensional weight is");
total=length*width*height/250;
System.out.print("total");
}
}
when I try to run it, the compiler tells methat the selection does not contain a main type, and that the local variable total does is never read, what am i doing wrong?

jorge3687 said:
Hi, I am just learning to program in java, i am using eclipse, I just wanted to apply something to what I have been reading, maybe I am getting ahead, but anyways, I wanted to create a program that measures dimmensional weight, you input the lenght, then the widht, and then the hight, take those numbers and multiply them by 250, that will give you the dimmensional weight, this is the code I created for that:
import java.util.Scanner;
class kilos {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
double length;
double width;
double height;
double total;
System.out.print("Length");
length=myScanner.nextDouble();
System.out.print("width");
width=myScanner.nextDouble();
System.out.print("height");
height=myScanner.nextDouble();
System.out.print("dimmensional weight is");
total=((length*width*height)/250);
System.out.print(total);
}
}
when I try to run it, the compiler tells methat the selection does not contain a main type, and that the local variable total does is never read, what am i doing wrong?
Click to expand...
Click to collapse
You had total in quotes. See my quote above, as I edited it.
As for no main, try adding public to it.
I added brackets on your sum as well for good practice. Also, I suggest setting all variables to 0 when being declared.
int count = 0;
That's all it takes, but if you ever use c++ this will be a good habit, since it won't clear your variables for you.
Hth

thanks, it worked, now i need to learn how to put it on my phone

Related

MapActivity, Buttons and OnClickListener

Hi all,
could you give me some help please? I have written a simple MapActivity that contains a mapview (defined in the xml file); it also contains a Button.
If the Button has no OnClickListener associated then the project runs fine (the mapview is of course empty).
If I add an OnclickListener the application simply Force closes.
Has anyone tried this? I was actually following the example in a book but I guess something has changed in the SDK since it was written?
I m using SDK 1.1 (for the moment).
If you have (recently) written something similar, could you give me some pointers please?
thanks
N
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
LOL
ehhehe
havent checked the log yet, will do and then report back here.
if anyone else has other suggestions please dont hesitate!
thanks
N
LogCat
Vlemmix said:
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
Click to expand...
Click to collapse
Vlemmix,
I checked the LogCat and seems too be a nullpointer indeed, but I cannot identify the mistake in the code.
This is the java source for the class. could you please have a look ?
If I un-comment the commented lines, I get a force close. Leave them uncommented and everything works (no click event on the button tho).
package com.chipset.testgps;
import com.google.android.maps.MapView;
import android.widget.Button;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
public class main extends MapActivity {
@Override
public boolean isRouteDisplayed(){
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button but = (Button) findViewById(R.id.gpsButton);
// but.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v){
//
// }
// });
final MapView map = (MapView) findViewById(R.id.myMap);
setContentView(R.layout.main);
}
}
Any help please??
thanks
N
1)
First do the setContentView, after that the Button is findable. The system could not find your Button now, so that's why it is a null. Your MapView map also would be a null in your code.
2)
If you define an object within {} it is only available within that {}
You probably going to need the Object "but" later, so make it a private variable of the class.
3)
Classname should start with a capital.
4) Visit anddev.org or some site like that for coding problems, xda seems to be more focused on system/firmware issues, not application code.
So, this should work:
public class MainActivity extends MapActivity {
final Button but;
final MapView map;
@Override
public boolean isRouteDisplayed() {
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but = (Button) findViewById(R.id.gpsButton);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
}
});
map = (MapView) findViewById(R.id.myMap);
}
}
Right
Hi Vlemmix.
Thanks very much for your help. I can understand what you are telling me, but if its so:
1) with the listener's lines commented, my code does show both the button and the mapview.. shouldnt it force close anyways if the problem is the setcontentView?
2) yeah agree with you on this one, though since I couldnt get even this simplest code to work, I didnt really want to overcomplicate it for now.
3) this is not a requirement is it? I mean its a coding convention, a good one yes, but not mandatory..?
4) Will do thanks, I m trying to get my bearings with all the dev websites etc.
PS about the API Key.. is this strictly required for developing on localhost (testing on the emu)? I find the info a bit confusing to be honest..
I will give your mods a shot this evening and will post here later tonight.
For the moment a big thank you for showing me my (silly) mistakes (I kinda miss .NET at times.. I wouldnt have messed up that bad with it..).
thanks!
N
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
ApiKey
Vlemmix said:
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
Click to expand...
Click to collapse
Will try and let you know mate!
The API Key you need to put in the xml for the MapView. apparently google has made this a requirement instead of the bogus key. I just dont understand if this is true also for the apps you test on the emu or only the ones that go 'live'..
Vlemmix
HI there,
just wanted to let you know that moving the setcontentview worked a treat!
Im so very embarassed now
thanks again for your help mate, I owe you one.
N
You're welcome, no problem!

[5/03] WPA-Enterprise WORKING for UT, UNSW, Georgia Tech

At this time, my courseload is way too high for me to do this. I also formatted and lost my sourcecode so I would have to write it from scratch. Sorry!
http://www.4shared.com/file/103246844/247a67c/WPA_Enterprise.html
Look below for instructions to request your school
Root, of course, is required.
The only other things this program needs is for the user to input their username and password as well as copy the security certificate to their SDcard as well as copying the security file to the SDcard. The program takes care of the rest.
I can modify my program to allow other people to connect to WPA Enterprise places in their area. If there is interest in this, let me know and I would be happy to upload versions of my program that allows others to connect.
Donations are always enjoyed
For UT Students:
1. Copy cacerts.pem to your SDCard. Make sure its named cacerts.pem NOT cacerts.pem or anything else similar. The program is CASE SENSITIVE. Make sure to UNMOUNT your sdcard from the computer
2. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your information.
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
For UNSW Students:
1. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your password (leave username blank)
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
For Georgia Tech Students
1. Copy Equifax_Secure_CA.pem to your SDCard. Make sure its named Equifax_Secure_CA.pem. The program is CASE SENSITIVE. Make sure to UNMOUNT your sdcard from the computer
2. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your information.
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
If anyone else wants it, link me to a page like this one and it will give me an example config.
Enjoy!
persiansown said:
I'm putting the finishing touches on my program that allows students that go to the University of Texas to connect to the WPA-Enterprise network here.
Root, of course, is required.
The only other things this program needs is for the user to input their username and password as well as copy the security certificate to their SDcard. The program takes care of the rest.
I can modify my program to allow other people to connect to WPA Enterprise places in their area. If there is interest in this, let me know and I would be happy to upload versions of my program that allows others to connect.
BTW, It definitely does work, I was able to connect to restricted.utexas.edu on my phone and browse the web through it.
Click to expand...
Click to collapse
Thats good news - I am interested - if this works, i'd be finally able to use it on my uni network.
btw - im on adb 1.5 official.
For those who are in a hurry:
http://forum.xda-developers.com/archive/index.php/t-450915.html
Cool Hook EM
Sorry I haven't uploaded the APK yet. I've been really busy with school and the like.
I need to put in a couple more lines so no one screws up their wifi. Expect it soon though
Fellow longhorn says "thanks in advance"
Sounds good, can finally connect to wifi @ my university
Program Released!
need a config pls
thanks alot for this.
here's a link for my uni : http://www.port.ac.uk/special/is/mobilemedia/broadband/wirelessoncampus/ -> its got the config details.
my uni operates on both wpa/wpa2 and the auth is peap, mschapv2
the cer certificate is on the windows xp part on the above link.
ive converted my .cer to .pem through openssl, so atleast one step is complete.
any help pls? thanks.
grippa said:
thanks alot for this.
here's a link for my uni : http://www.port.ac.uk/special/is/mobilemedia/broadband/wirelessoncampus/ -> its got the config details.
my uni operates on both wpa/wpa2 and the auth is peap, mschapv2
the cer certificate is on the windows xp part on the above link.
ive converted my .cer to .pem through openssl, so atleast one step is complete.
any help pls? thanks.
Click to expand...
Click to collapse
I can try that. Im not sure, but Ill try to wing it for you. Ill send you a PM when its uploaded.
If you could try to do the same for these settings that would be awesome =]
http://www.it.unsw.edu.au/services/uniwide/mobile_devices.html
smurphete said:
If you could try to do the same for these settings that would be awesome =]
http://www.it.unsw.edu.au/services/uniwide/mobile_devices.html
Click to expand...
Click to collapse
We've got the same settings here for WPA-Enterprise, only the SSID is "OpenWLAN". (WPA-TKIP / WPA2-AES (Enterprise) & EAP (PEAP and MS-CHAPv2))
Do you think there is a way to do this?
Please post the source. I suggest that other UT students refrain from using this application until then, due to the ridiculously high abuse potential of an app that elevates to root, and even worse, one that you enter EID + password in.
The normal restrictions on network access can be sidestepped. Your EID and password could easily be harvested. Don't run apps like this until the source is available and someone reputable looks at it.
I posted UT Austin specific instructions back in November. If you want access at UT but don't like to gamble, feel free to give them a try. They're a bit dated with respect to gaining root.
http://forum.xda-developers.com/showthread.php?t=450915
I'll add also that the instructions will probably work at any location using WPA Enterprise auth - anything that wpa_supplicant supports. There are several examples in my thread of people getting it to work at their school/workplace. You can either create the configuration file yourself by looking at the Windows/Mac/whatever instructions made available to you, or you may try contacting the local IT dept.
package com.test.login;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class Login extends Activity {
// Declare our Views, so we can access them later
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnInstall;
private Button btnUndo;
private Button btnRestart;
private String username;
private String password;
private String securityfilename = "cacerts.pem";
private boolean copied = false;
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
command("cp /data/misc/wifi/wpa_supplicant.conf /sdcard/wpa_supplicant.conf");
command("cp /data/misc/wifi/wpa_supplicant.conf /sdcard/wpa_supplicant.conf.bac");
super.onCreate(savedInstanceState);
// Set Activity Layout
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.username);
etPassword = (EditText)findViewById(R.id.password);
btnLogin = (Button)findViewById(R.id.login_button);
btnInstall = (Button)findViewById(R.id.install_button);
btnRestart = (Button)findViewById(R.id.restart_button);
btnUndo = (Button)findViewById(R.id.undo_button);
// Spinner array
final Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.locations, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
action("WARNING!","If you have superuser installed, you MUST click ALWAYS before continuing.\n \nOtherwise I'm not sure what may happen\n\nMake sure your Security Certificate is on your SDcard");
// Set Click Listener
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Check Login
username = etUsername.getText().toString();
password = etPassword.getText().toString();
action("Step 1 Complete","Input Successful\nIf phone is in landscape, change to portrait and click again ");
String place = (String) s.getSelectedItem();
inputvalues (username, password, place);
}
});
btnInstall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
command ("cp /sdcard/" + securityfilename + " /data/misc/wifi/" + securityfilename);
command ("cp /sdcard/wpa_supplicant.conf" + " /data/misc/wifi/wpa_supplicant.conf");
command ("chmod 666 /data/misc/wifi/wpa_supplicant.conf");
command ("chmod 444 /data/misc/wifi/cacerts.pem");
copied = true;
try {
Thread.sleep(2500);
}
catch(InterruptedException e) {}
action("Step 2 Complete","Config Saved Successfly");
}
});
btnRestart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(copied)
command ("reboot");
}
});
btnUndo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
command ("cp /sdcard/wpa_supplicant.conf.bac" + " /data/misc/wifi/wpa_supplicant.conf");
}
});
}
public void command (String inputcommand)
{
Process process = null;
DataOutputStream os = null;
try
{
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(inputcommand);
os.flush();
os.close();
}
catch (Exception e)
{
return;
}
finally
{
try
{
if (os !=null)
{
os.close();
}
}
catch (Exception e) {}
}
}
public void inputvalues (String usrname, String pswrd, String location)
{
if (location=="University of Texas at Austin");
{
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("/sdcard/wpa_supplicant.conf", true));
writer.newLine();
writer.write("fast_reauth=0");
writer.newLine();
writer.write("network={");
writer.newLine();
writer.write("\t ssid=\"restricted.utexas.edu\"");
writer.newLine();
writer.write("\t key_mgmt=WPA-EAP");
writer.newLine();
writer.write("\t eap=TTLS");
writer.newLine();
writer.write("\t ca_cert=\"/data/misc/wifi/" + securityfilename + "\"");
writer.newLine();
writer.write("subject_match=\"CN=restricted.utexas.edu\"");
writer.newLine();
writer.write("\t anonymous_identity=\"anonymous\"");
writer.newLine();
writer.write("\t identity=\"" + usrname + "\"");
writer.newLine();
writer.write("\t password=\"" + pswrd + "\"");
writer.newLine();
writer.write("\t phase2=\"auth=MSCHAPV2\"");
writer.newLine();
writer.write("}");
writer.newLine();
writer.newLine();
writer.flush();
writer.close();
}
catch(FileNotFoundException ex){}
catch(IOException ioe){}
}
}
public void action (String step, String title)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(step);
alert.setMessage(title);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//cancel
}
});
alert.show();
}
}
Click to expand...
Click to collapse
Here is my source. There is an XML portion that takes care of the interface.
To be truthful, I'm kind of embarrassed of the code because I haven't touched Java since highschool. There is nothing wrong with this application, and nothing nefarious. To be honest, I wouldn't know how to do something like that if I wanted since I would have to delve into the commands.
If you have any suggestions for my code, I would be happy to hear them.
I took up this application as a side product just to see if my knowledge of linux was strong enough (I used linux on my netbook for a while before switching to windows 7) and once I got it working I wanted to share it with the community that has given me so much on both my current phone and previous ones.
Anyway, to all the people in this thread who are requesting stuff:
My birthday is today and my girlfriend came up to UT to celebrate with me. She won't be leaving until Sunday so.... I won't be working on it until Sunday. Bear with me though, I will get it up for you guys if I can (again, I pretty much suck. But now that the framework is down, I think I know what to do)
Smurfette, I took a look there and I'm pretty sure I can do it for you
Georgia Institute of Technology Pilot WPA Program
http://www.lawn.gatech.edu/help/gtwpa/
These are the instructions about signing on to WPA at my university. I will look at modifying the source myself, but I don't have time either at the moment. Just curious--how many other GT students are using XDA-developers to mod their Dream??
So far I am sure I can do it for ellingthepirate and smurphete. I found example configurations for those two. I'm not sure about N23 or the guy on the other page yet. Again, I won't be able to update the app until sunday night (central time) at the earliest.
Will this eventually work with the *.cer certificates?
Hi Persiansown,
I am working on something similar. Can you tell me how did you get permission to create/modify wpa_supplicant.conf programatically?
THANK YOU SO MUCH!!
zhang42 said:
Hi Persiansown,
I am working on something similar. Can you tell me how did you get permission to create/modify wpa_supplicant.conf programatically?
THANK YOU SO MUCH!!
Click to expand...
Click to collapse
Never mind! I've figured it out!
Updated for University of South Wales and Georgia Tech

[Q] choose array-elements with certain probability

hello,
I'm writing a Android App (java) - but I guess this question is pretty general, and isn't java-specific:
so I have an Array of Elements
and I let a random-number-generator pick one array-element randomly and hand it to me.
now I've also built in a "score"-field into each array Element
so what I want to do now, is that the random-number-generator takes the array's "score" in consideration, and gives me the array-elements with the higher/lower scores with a higher/lower probability
I dont want it to ALWAYS/NEVER give me the elements with the highest/lowest score - just with a higher/lower probability
I hope I could describe my problem in a proper way....
does anybody know how to achieve this?
(as I said, i use java, but i guess code in any language - or even pseudo-code would help me out)
*bump*
anybody?
Try this, it's in C# but it's pretty close to Java.
You cannot directly weight the random function so you have to use a different method.
By applying a weight to each item in the array, then using a random function to select using the weighting values, the results of the selection can be swayed.
The weighting values are relative to each other.
Using the values in the code, 'B' should turn up about three times more often than 'A'
The only object that may need some explanation is Random:
http://msdn.microsoft.com/en-us/library/system.random(v=VS.80).aspx
Code:
using System;
namespace RandomWeighting
{
class Program
{
static void Main(string[] args)
{
char[] Select = new char[10] {'A','B','C','D','E','F','G','H','I','J'};
int[] Weight = new int[10] {10,30,25,60,20,70,10,80,20,30};
int[] WeightSum = new int[10];
int i,j,k;
Random Rnd = new Random();
WeightSum[0]=Weight[0];
for (i = 1; i < 10; i++)
WeightSum[i] = WeightSum[i - 1] + Weight[i];
for (j = 0; j < 70; j++)
{
k = Rnd.Next(WeightSum[9]);
for (i = 0; k > WeightSum[i]; i++) ;
Console.Write(Select[i]);
}
Console.WriteLine();
}
}
}
Output:
Code:
HEFIBHHCCFBCAEFFDHACHBEJHHFDFIDFEDFFCHHDJBIDJEHHFHCJJJBHJGBDDGFDDFHHHB
Note the low density of A and G as opposed to H
It is just a sample at random, but 2 'A's and 7 'B's roughly matches the conjecture above, but over a million selections, the distribution is as follows:
Code:
A 30664
B 84187
C 70648
D 168481
E 56529
F 197311
G 28145
H 225764
I 56613
J 81658
If your code changes values in the Weight array then the WeightSum array must be recalculated.
wow, thats a lot!
The only thing I dont understand about the code is this line:
k = Rnd.Next(WeightSum[9]);
for (i = 0; k > WeightSum; i++) ;
what exactly happens here?
what kind of a for-loop is this?
why is there no body?
and strangely, while debugging this line, i noticed that the value of i jumps to some random number in this line - and I have no idea why and how
------
by the way: I've already tried it out, it works pretty good.
although I noticed that the first element always gets picked ALOT, no matter how low the weight.
I think thats a flaw in the algorithm
After the following code:
Code:
for (i = 1; i < 10; i++)
WeightSum[i] = WeightSum[i - 1] + Weight[i];
The WeightSum array contains the following values:
Code:
[0] 10
[1] 40
[2] 65
[3] 125
[4] 145
[5] 215
[6] 225
[7] 305
[8] 325
[9] 355
The Random.Next() function that takes a single integer as an argument is defined as:
-------- Courtesy of MS VS .NET Help ------
public virtual int Next(int maxValue)
Parameters maxValue Type: System.Int32
The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to zero.
Return Value Type: System.Int32
A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.
-------------- End of Help ----------------
So, we are asking for a random value between 0 and 354,(element WeightSum[9] above). The following code then finds which is the lowest element of WeightSum which holds a value greater than the one we have been given. When this happens 'i' contains the index to use for the selection.
Code:
for (i = 0; k > WeightSum[i]; i++);
The standard construction of a for loop in C is
for(One or more initialisation statements; Do_While_True Condition; One or more iteration statements)
{
loop processing code;
}
If there is nothing to do in the loop body, you don't need it, and you can replace it with the ';' at the end of the for statement. In effect, it is identical to the following code:-
Code:
i=0;
while(k > WeightSum[i])
{
i++;
}
As regards the first element being picked more than the others, have a look at the distribution table in post #3. It is what you would expect for the values given. I assume the difference is either the Random function in Java or some different implementation between C# and Java.
You may have to change some of the code slightly, i.e. change the for() loop to the while() loop above and step though it in the Java debugger to get to the root of the problem.
You can't debug a for loop followed by an immediate ';' The entire for loop is executed to completion when you use debug and try and step through it. To debug it place a dummy statement in the for loop. A breakpoint may now be set on this line.
Code:
int i,z;
for (i = 0; k > WeightSum[i]; i++)
{
z=0;
}
ActionScript and Javascript versions ...
Thanks for the great write-up! In case anyone is interested, I've adapted this into a javascript and ActionScript class. If anyone is interested, I've attached the code. For a more in-depth post, check out blog.teamthinklabs.com.
Cheers!
Kipp Ashford
Art Director
Seven2 Interactive

Java homework..

I missed one class of my java programming class, and now i do not know what to do at all. If anyone could do the problems for me, i would be grateful. Before i get bashed for having someone do my homework, i can learn really easy if someone does it for me, and i can work out how they did it through a matter of trial and error.
Thank you.
Everything you need to know about the Java String class is on this page, including a few samples that are very similar to your assignment.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
I still don't understand it. I can only learn when someone shows me, so unless someone here can do it i guess i have to turn it in as a zero.
Answer to 1. is here 2 and 3 are up to you.
Code:
class StringApp {
public static void main(String[] args) {
String str,str1,str2,str3;
int length;
str="CSE 201";
length=str.length();
str1="ABC";
str2="XYZ";
str3=str1.concat(str2);
}
}
P.S. I've never written a line of Java code before. Luckily it is not that far from C#.
Thank you! Two more problems left.
Awwwwww....... What the hell.....
Answers to 2 and 4:
Code:
class TestApp
{
public static void main(String[] args)
{
String phrase = "To be or not to be";
String anotherPhrase="not";
String longphrase;
String today ="Tuesday,January 18";
int commapos;
System.out.printf("a. %s is %d characters long.\n",phrase, phrase.length());
System.out.printf("b. %d\n",phrase.indexOf(anotherPhrase));
System.out.printf ("c. %s\n",phrase.substring(3, 12));
longphrase=phrase + ", that is the question.";
System.out.printf ("d. %s\n",longphrase);
System.out.printf("e. %d\n",phrase.indexOf("Alien"));
System.out.printf("f. %c\n",phrase.charAt(0));
System.out.printf("g. %c\n",phrase.charAt(phrase.length()-1));
commapos=today.indexOf(",");
System.out.printf("Today is %s. What a great %s!\n",today.substring(commapos+1),today.substring(0,commapos));
}
}
When run produces:-
Code:
a. To be or not to be is 18 characters long.
b. 9
c. be or not
d. To be or not to be, that is the question.
e. -1
f. T
g. e
Today is January 18. What a great Tuesday!
Question 3.
c. str.charAt(0); // str. missing
d. int n=str1.indexOf(str2); // dot missing between str1 and IndexOf()

Application for notify when your flat is power-less

Hi everyone
I was searching one app for android, but i cannot find any like that.
Basically i need to understand when my flat went down on electricity
beacuse i have food in the fridge, fish in the acquarium or whatever you may have.
I was thinking i could leave a currently unused phone on charge in the wall socket.
When electricity goes off the phone stop charging and it can notify me with email.
Do you think something like that exist?
A general event driven notifier that support email would be fine.
Is there anything like that? on the market even a paid app?
Best regards, Andrea
You could try using Tasker for it.
"To err is human, to forgive is divine"
Sent from my SGS II
Tasker do half of the job...
it detects what i need, it compose the email...
but it cannot send it!!!
It can open a web url directly, so i can program a simple php script to send an email.
But if i could do without a webserver helping me it would be better.
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
qubas said:
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
Click to expand...
Click to collapse
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
asturur said:
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
Click to expand...
Click to collapse
There are many tutorials for installing Android Development Tools (ADT) and creating simple "Hello world" app. It probably takes 1 hour to do that. For simple app you don't really have to know Java, copy-paste some code samples from the Internet should do the trick, you just need to have at least some basic programming knowledge.
I still think that sending SMS is the most reliable solution. Using Wifi is a bad idea, because it won't work when there is no AC, unless you have a UPS. With 3G its much better, but still you have to rely on the web service you use to send email.
Anyway, here is my code:
Code:
package com.example.powermonitoring;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String NUMBER = "+48123456789";
private static final int THRESHOLD = 10;
private static final String AC_ONLINE = "AC is back online!";
private static final String AC_OFFLINE = "AC is offline!";
private Handler handler = new Handler();
private int counter;
private boolean lastPowerState;
private boolean powerState;
private Runnable runnable = new Runnable() {
[user=439709]@override[/user]
public void run() {
powerState = isPlugged(MainActivity.this);
if (powerState != lastPowerState) {
counter++;
if (counter == THRESHOLD) {
counter = 0;
lastPowerState = powerState;
String message;
if (powerState) {
message = AC_ONLINE;
} else {
message = AC_OFFLINE;
}
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); //for testing
//SmsManager sms = SmsManager.getDefault();
//sms.sendTextMessage(NUMBER, null, message, null, null);
}
}
handler.postDelayed(this, 1000);
}
};
public static boolean isPlugged(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastPowerState = isPlugged(MainActivity.this);
handler.postDelayed(runnable, 1000);
}
}
You just have to remember about including permission in AndroidManifest.xml :
Code:
<uses-permission
android:name="android.permission.SEND_SMS"
/>

Categories

Resources