Hey all,
So Im a newbie learning Java and I am trying to take what I have learned and complete a simple project I came up with. Im just working working on a basic BMI calculator. I have to issues.... I cant get it to print the result and my scanner shows a output code when I run the program. Could somebody take a look and give me advice?
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args) {
Scanner height = new Scanner(System.in);
startC startCObject = new startC();
System.out.println("Enter your height:");
System.out.println(height);
String temp = height.nextLine();
startCObject.setHeight(temp);
Scanner weight = new Scanner(System.in);
System.out.println("Enter your Weight:");
System.out.println(weight);
String temp1 = weight.nextLine();
startCObject.setWeight(temp1);
Scanner result = new Scanner(System.in);
System.out.println("BMI:" + result);
}}
Click to expand...
Click to collapse
and
public class startC {
//HEIGHT
private String enterH;
public void setHeight(String height) {
enterH = height;
}
public String getHeight() {
return enterH;
}
//WEIGHT
private String enterW;
public void setWeight(String weight) {
enterW = weight;
}
public String getWeight() {
return enterW;
}
//RESULT
private String ht, wt;
public void resHeight(String height) {
ht = height;
}
public String resheight() {
return ht;
}
//then
public void resWeight(String weight) {
wt = weight;
}
public String resweight() {
return wt;
}
//then
public String result; {
result = ht + wt;
}
public String getResult(String result) {
return result;
}
}
Click to expand...
Click to collapse
I don't think you can print a Scanner?
Also, you can use just one Scanner for both inputs, and it is good to also close them with scannerName.close(); when finished.
Try and get that sorted, then see what happens? Please post your code in the
Code:
and
tags too, then .
bassie1995 said:
I don't think you can print a Scanner?
Also, you can use just one Scanner for both inputs, and it is good to also close them with scannerName.close(); when finished.
Try and get that sorted, then see what happens? Please post your code in the
Code:
and
tags too, then .
Click to expand...
Click to collapse
Ah; sorry about that, and thank you for the info.
I actually ended up tearing the code down and rethinking it. I was making it far more difficult than it needed to be.
Here is what I have now which is working perfect. Pretty excited considering this is the first project I've done on my own.!
Code:
import java.util.Scanner;
public class theCalc {
public static void main(String[] args) {
// feet
System.out.println("Enter your height (Feet):");
Scanner scan = new Scanner(System.in);
double feet = scan.nextDouble();
// inches
System.out.println("Enter your height (Inches):");
double inches = scan.nextDouble();
// weight
System.out.println("Enter your weight:");
double weight = scan.nextDouble();
// convert to inches
double height = feet * 12 + inches;
// height squared
double htsqr = height * height;
// BMI formula
double htInchByWeight = weight / htsqr;
double BMI = htInchByWeight * 703;
// BMI =
System.out.println("Your BMI is: " + BMI);
}
}
Was thinking it to be a bit too complicated, but a good exercise with multiple classes and such. It looks much better now, and glad you got it working!
Sent from my GT-I9300 using Tapatalk 4 Beta
Related
Can someone make a .cab or an .exe program to calculate Weight Watchers points? I found this article on the internet where it looks like someone as already done it but they did not post it. Here is the article
http://geekswithblogs.net/cdahlinge...-mobile-meets-weight-watchers--mvp-style.aspx
Craig Dahlinger
<< Presenting at Richdmond code camp 2008.2 | Home | mshtml β the ongoing adventure >> windows mobile meets weight watchers : MVP style Ok, so I know it has been a long time since a post, but it has been really busy with work and family. I have been busy coding and learning lots of new stuff. I work with a great bunch of developers and my current team lead is a great mentor.
Well for the new year the wife and I decided to get back into shape. I started hitting the gym and so did she but she is also doing weight watchers with a friend. One of the things they do is they have to calculate points on a daily basis. These points are comprised of calories, fat and fiber. There is a formula for these three which in turn results in the number of points a particular item is. A few months ago I convinced the wife to get a windows mobile device (woo hoo!) and she is a good power user. So one night she asks me, βIs there a way I can just enter in the calories, fat and fiber on my phone and it tell me how many points something is?β. I did some searching and there are numerous online versions of the calculator but no native ones for windows mobile. I found the formula here, and started to get to work.
I wanted to approach this application using the MVP design pattern. I know it may be overkill for this simple of an application but I thought it would be good practice.
I started with the interface for the data model, in this case it would be the main caloric properties of food.
namespace WWPC.Common.Interfaces{ public interface IFoodModel { int Fiber { get; set; } int Calories { get; set; } float Fat { get; set; } int Points { get; set; } int CalculatePoints(); }}I then wrote up the interface for the view for the model.
namespace WWPC.Common.Interfaces{ public interface IFoodCalcView { int Calories { get; } int Fiber { get; } float Fat { get; } int Points { set; } event EventHandler DataChanged; }}Next, came the interface for the presenter.
public interface IFoodCalcPresenter { void OnCalculatePoints(); }
Ok, now that I got my main interfaces in place, time to code up the implementation. I started with the model first since this was the class that would provide the implementation for calculating the caloric points. Using the formula mentioned above, the CalculatePoints() method came out like so:
public int CalculatePoints(){ var calories = Convert.ToDecimal(Calories); var cal = calories / 50; var totalFat = Convert.ToDecimal(Fat); var fat = totalFat / 12; var fiber = Convert.ToDecimal(Fiber); return Points = Convert.ToInt32(Math.Round(cal + fat - (fiber/5), 0)); } With the model complete, I then moved to the presenter. The presenter would be responsible for binding the model to the view responding to the data changes in the view and rebinding those changes to the model. I made the presenter with an overloaded constructor to take a view and a model. The presenter then binds to the data changed event on the view which enables the presenter to update the model from the view. The OnCalculatePoints() method will update the view with the points value after using the model for calculation.
namespace WWPC.Common{ public class FoodPresenter : IFoodCalcPresenter { private readonly IFoodCalcView _View; private readonly IFoodModel _Model; public FoodPresenter(IFoodCalcView view, IFoodModel model) { _View = view; _View.DataChanged += new EventHandler(_View_DataChanged); _Model = model; } void _View_DataChanged(object sender, EventArgs e) { SetModelFromView(); } private void SetModelFromView() { _Model.Calories = _View.Calories; _Model.Fat = _View.Fat; _Model.Fiber = _View.Fiber; } #region IFoodCalcPresenter Members public void OnCalculatePoints() { _View.Points = _Model.CalculatePoints(); } #endregion }}
With the presenter done it was time to implement the view. I wanted a simple mobile form where you can enter in data quickly and then calculate the results. I initially tried using a label to display the result, but did not like it. I then tried a mobile gauge control, but that took up too much space on the small screen. Finally I decided to use the notification class for windows mobile. I did not use the managed wrapper version, I used the the version created by Christopher Fairbairn, found here. This version has an awesome implementation which exposes many features of the notification class. I wanted to give the user the ability to dismiss the notification when they were done reading the results. Also using the notification class the UI was able show the needed text boxes for entry and the SIP panel along with the results without needing to scroll the screen. Here is a screen shot of the main form.
Now with the controls in place on the form, I can implement the view. The form creates a new presenter and passed into it a new model during construction. When the calculate menu option is clicked the main form raises the data changed event then calls the OnCalculateMethod on the presenter. When the presenter binds the model to the view, during the set of the points value, the notification is shown to the user via the ShowNotification method.
namespace WWPC.Calc{ public partial class WWPCalculator : Form, IFoodCalcView { private readonly FoodPresenter _Presenter; private NotificationWithSoftKeys _Notification; public WWPCalculator() { InitializeComponent(); _Presenter = new FoodPresenter(this,new FoodModel()); } public int Calories { get { return (string.IsNullOrEmpty(txtCalories.Text)) ? 0 : Int32.Parse(txtCalories.Text); } } public int Fiber { get { return (cmbFiber.Text == "4 or more") ? 4 : (string.IsNullOrEmpty(cmbFiber.Text)) ? 0 :Int32.Parse(cmbFiber.Text); } } public float Fat { get { return (string.IsNullOrEmpty(txtFat.Text)) ? 0 : float.Parse(txtFat.Text); } } public int Points { set { ShowPointsNotification(value); } } public event EventHandler DataChanged; private void mnuExit_Click(object sender, EventArgs e) { this.Close(); } private void mnuCalculate_Click(object sender, EventArgs e) { if (DataChanged != null) this.DataChanged(sender, e); _Presenter.OnCalculatePoints(); } private void mnuClear_Click(object sender, EventArgs e) { txtCalories.Text = string.Empty; txtFat.Text = string.Empty; cmbFiber.Text = "0"; } private void ShowPointsNotification(int points) { _Notification = new NotificationWithSoftKeys { Text = String.Format("Total Points:{0}", points), Caption = "Weight Watchers Point Calculator", RightSoftKey = new NotificationSoftKey(SoftKeyType.Dismiss, "Dismiss"), }; _Notification.RightSoftKeyClick+=new EventHandler(_Notification_RightSoftKeyClick); _Notification.Visible = true; } void _Notification_RightSoftKeyClick(object sender, EventArgs e) { if (_Notification == null) return; _Notification.Visible = false; _Notification = null; } }}
Now, when it is all put together, it looks like so.
Below is a link to the source code. The project was done using Visual Studio 2008 against the windows mobile 5 sdk. It will also work against windows mobile 6 sdk, I just chose version 5 since that is the common sdk. Thanks for reading!!
Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.
I have a little problem with my equations while using a spinner. What happens is user chooses option from spinner then enters three separate numbers in different EditText the calculation will perform as soon as the user hits the calculation button.
the originally return of the calculation is 0.0. until you again choose an option from the spinner and click calculate again. which then returns the correct answer.
thanks ahead of time.
Is there supposed to be a question in there somewhere?
Yeah sorry,
I guess I forgot to add the question.
Does anyone now why this is happening? should I put the onItemSelectionListener before the onClick. that part of the code looks somethink this.
Code:
btnCalc.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if ((ageEdit.getText().toString()== " " )
||(ageEdit.getText().length()== 0 )
||(heightEdit.getText().toString()== " ")
||(heightEdit.getText().length()== 0 )
||(weightEdit.getText().toString()== " ")
||(weightEdit.getText().length()== 0 )
)
{
showErrorAlert("Some Input are empty!",
input.getId());
}
else {
height = Double.parseDouble(txtwlHeight2.getText().toString());
weight = Double.parseDouble(txtwlWeight.getText().toString());
age = (int) Double.parseDouble(txtageinput01.getText().toString());
spnGender.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onNothingSelected(AdapterView<?> arg0){}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub{
switch (position){
case 0:
//some equation
break;
case 1:
//some equation
break;
}
}
});
// etc. such calculation out to text view.
Any Idea's anyone? I've does a lot of research and reading. Tried to re write code in different ways still no luck.. need help please.
Hello Boys,
I am a new Android developer and I'm developing an app with the API of Google Maps.
Into an area of the map I place many markers.
The application works correctly, but the map scroolling and the map zoom isn't quick, everything goes slow.
The marker that I have included in the map is in the "png" format image, and his weighs is approximately 600 bytes.
it is possible that many marker object cause low map scrool?
this is the code of my APP:
Code:
plublic class IDC extends MapActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private MapController mc;
private MapView mapView;
private String myPosition;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String errore="";
myPosition="";
try{
mapView = (MapView) findViewById(R.id.mapview);
mc = mapView.getController();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
//getMyLocation();
MyDBHelper myDB = new MyDBHelper(IDS.this);
Cursor cursor= myDB.query(new String[] { "x", "y", "y2", "w", "k", "latitude", "longitude"});
//Log.i("NOMI", "TOT. NOMI"+cursor.getCount());
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mm_20_blue);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,IDS.this);
List<Address> address = new ArrayList<Address>();
Log.i("TOT TUPLE", " = "+cursor.getCount());
while(cursor.moveToNext()){
String s= cursor.getString(0);
errore=s;
String nome[]=s.split("-");
// Log.i("Pos Colonna NOME", ""+cursor.getColumnIndex("nome"));
// Log.i("Pos. in Colonna", ""+cursor.getString(0));
//address.addAll(gc.getFromLocationName(nome[1], 1));
//Address a= address.get(address.size()-1);
String la=cursor.getString(5);
String lo=cursor.getString(6);
double latitude= Double.parseDouble(la);
double longitude= Double.parseDouble(lo);
int lan= (int)(latitude*1E6);
int lon= (int)(longitude*1E6);
GeoPoint point = new GeoPoint(lan, lon);
String tel1=cursor.getString(1);
String tel2=cursor.getString(2);
String mail=cursor.getString(4);
String web=cursor.getString(3);
String info[]= {tel1,tel2,nome[1],web,mail};
MyOverlayItem overlayitem = new MyOverlayItem(point, "Hello", nome[0], info);
//mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
mapView.setBuiltInZoomControls(true);
mc.setZoom(6);
}catch (Exception e) {
e.printStackTrace();
}
}
}
Code:
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
private CustomizeDialog customizeDialog;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public MyItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
protected boolean onTap(int index)
MyOverlayItem item = (MyOverlayItem) mOverlays.get(index);
customizeDialog = new CustomizeDialog(mContext);
customizeDialog.setPersonalText(item.getSnippet());
String []info= item.getInfo();
customizeDialog.setT1(info[0]);
customizeDialog.setT2(info[1]);
customizeDialog.setA(info[2]);
customizeDialog.setW(info[3]);
customizeDialog.setM(info[4]);
customizeDialog.show();
return true;
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
}
what is the problem??....PLEASE, HELP ME!!
For my App I want when you click into the autocompletetextview it will bring up a list of chemicals and then when you choose your chemical it will put the chemical name in the autocomplete field and also put the corresponding weight into an edittext field.
The approach I went with this was using a customadapter so when you pick one it will give the other. It is my first time making one so I'm not sure if it's 100% correct. It would be great if you guys had any suggestions. Thanks
Currently this is the code that I have.
editText4 is the autocompletetextview field I want the chemical name to appear in.
editText is the editText field i want the number to appear in.
MainActivity .java
Code:
public void Chem() {
Chemical chemical_data[] = new Chemical[]
{
new Chemical("Acid", 125.33),
new Chemical("Blue", 145.3356),
};
ChemicalAdapter adapter = new ChemicalAdapter(this, R.layout.sollayout, chemical_data);
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
weightval = (EditText) findViewById(R.id.editText);
//ChemicalAdapter header = new ChemicalAdapter(this, R.layout.sollayout, null);
//weightval.addHeaderView(header);
chemname.setAdapter(adapter);
}
public void Chemname()
{
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
AutoCompleteTextView b = (AutoCompleteTextView) findViewById(R.id.editText4);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Chem();
}
});
}
Chemical.java
Code:
public class Chemical {
String chemicalValue;
double weight;
public Chemical(String chemicalValue, double weight) {
this.chemicalValue = chemicalValue;
this.weight = weight;
}
public String getChemicalValue() {
return chemicalValue;
}
public double getWeight() {
return weight;
}
}
ChemicalAdapter.java
Code:
public class ChemicalAdapter extends ArrayAdapter<Chemical> {
Context context;
int layoutResourceId;
Chemical data[] = null;
public ChemicalAdapter(Context context, int layoutResourceId, Chemical[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChemicalHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChemicalHolder();
holder.chemname = (AutoCompleteTextView)row.findViewById(R.id.editText4);
holder.weightval = (EditText)row.findViewById(R.id.editText);
row.setTag(holder);
}
else
{
holder = (ChemicalHolder)row.getTag();
}
Chemical chemical = data[position];
holder.weightval.setText(String.valueOf(chemical.weight));
holder.chemname.setText(chemical.chemicalValue);
return row;
}
static class ChemicalHolder
{
AutoCompleteTextView chemname;
EditText weightval;
}
}