Guess and Check algorithm dart language - dart

I want to learn dart programming language for mobile and web development. I tried to solve writing some algorithm in dart language, guess and check algorithm is very basic but I could not run it. Please help me.
Here is my code:
import 'dart:math';
void main() {
int cube = 27;
double epsilon = 0.1;
double guess = 0.0;
double increment = 0.01;
int num_guess = 0;
while ((pow(guess, 3).abs() - cube) >= epsilon) {
guess += increment;
num_guess++;
print("num_guess =" + " " + num_guess.toString());
}
if ((pow(guess, 3).abs() - cube) >= epsilon) {
print("Failed on cube root of" +
" " +
cube.toString() +
" " +
guess.toString());
} else {
print(guess.toString() + " " + "is close to the cube " +
cube.toString());
}
}

Related

How do I find the Distance between two points while avoiding the error "NumberFormatException"?

I want to find the distance between two points but when I convert the string into an int I cant seem to resolve the error, "NumberFormatException".
import java.util.Scanner;
public class Code{
static Scanner scanner = new Scanner(System.in);
public static void main(String\[\] args){
String coords = scanner.next();
int a = Integer.parseInt(coords);
int b = Integer.parseInt(coords);
int c = Integer.parseInt(coords);
int d = Integer.parseInt(coords);
int x = b-a;
int y = d-c;
double distance = Math.sqrt(x*x + y*y);
System.out.println("The distance between (" + a + ", " + b + ") and (" +
c + ", " + d + ") is " + distance);
}
}

double datatype behaving in an undefined manner

Even though I know turbo c is completely obsolete now, my instructor has put a condition to code in it.
I am having an issue that when I am trying to pass a double value to a function it is not behaving properly. I am getting fluctuating output several of the time, sometimes even weird. Let's see my code first:
#include<stdio.h>
#include<conio.h>
double func(double input) {
return input * input;
}
double simpson1By3(double initial, double final, double parts) {
double sum = 0;
double h = (final - initial) / parts;
double oddSum = 0, evenSum = 0;
int i;
printf("%f %f %f\n", initial, final, parts);
printf("%f\n", h);
printf("%f %f\n", evenSum, oddSum);
sum += func(initial) + func(final);
printf("%f %f\n", evenSum, oddSum);
for (i = 1; i < parts; i = i + 2) {
oddSum += func(initial + (i * h));
}
for (i = 2; i < parts; i = i + 2) {
evenSum += func(initial + (i * h));
}
oddSum *= 4;
evenSum *= 2;
printf("%f %f\n", evenSum, oddSum);
sum += evenSum + oddSum;
sum *= h / 3;
return sum;
}
int main() {
clrscr();
printf ("%f", simpson1By3(0, 6, 6));
getch();
return 0;
}
sample output:
What am I doing wrong there? Why are the arguments passed printed erroneously there along with other variables there and why is that -0 printing? Please help. I have tried finding something similar to it in forums but completely failed. Please help.

TIdHTTP GET Round Trip Request/Response Time in MSecs

I'm using TIdHTTP to make HTTP GET requests to get wiki pages (executed until x >= 9 times using a for loop statement).
I am trying to use TStopWatch to measure the HTTP round trip request/response time in milliseconds of each GET requests.
I have tried somes methods, but, I still in doubt that it was right or not. So, please tell me what's the right method to do that. Thank you.
Btw, the code I have is:
//---------------------------------------------------------------------------
int MSec = 0;
TTimeSpan TTSpan;
TDateTime StartTime;
DWORD AStartTime = 0;
DWORD CStartTime = 0;
String ACount, Codes, Milli, Result;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
IdHTTP->ConnectTimeout = 3048;
IdHTTP->ReadTimeout = 2048;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
if (AWorkMode == wmRead)
ACount = "size: [" + String(AWorkCount) + " bytes]";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WorkClick(TObject *Sender)
{
static int Number = 1;
TStopwatch SWatch = TStopwatch::StartNew();
// CStartTime = GetTickCount();
// DWORD Start = timeGetTime();
// AStartTime = GetTickCount();
// CStartTime = TTSpan.Milliseconds;
Work->Enabled = false;
ListBox->Items->Clear();
ListBox->Items->BeginUpdate();
for (int i = 0; i < 9; i++)
{
try
{
SWatch.Start();
try
{
IdHTTP->Get("http://en.wikipedia.org/");
Sleep(1000);
}
catch (const Exception &E)
{
Label1->Caption = E.Message;
}
SWatch.Stop();
TTSpan = SWatch.Elapsed;
MSec = TTSpan.Milliseconds;
// MSec = TTSpan.Milliseconds / 10;
// MSec = SWatch.ElapsedMilliseconds / 10;
// TTSpan = SWatch.Elapsed;
// MSec = TTSpan.Milliseconds - CStartTime;
Milli = " time: [" + String(MSec) + " ms]";
Codes = " code: [" + IdHTTP->Response->ResponseText.LowerCase() + "]";
ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Milli);
// AStartTime = GetTickCount();
// ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Result.sprintf(L" time: [%i ms]",(aStartTime-bStartTime)));
}
__finally
{
Work->Enabled = true;
IdHTTP->Disconnect(true);
ListBox->Items->EndUpdate();
}
}
}

JtextField Variable Grab and Use for Numerical Iteration from GUI

this is my complete code for a small gui to take variables from user and return them to the rest of program(r.o.p) for calculations, however doesn't seem to be passing to r.o.p. and no output file is observerd.
Any help would be much appreciated, I think the problem is with the listener for the Draw New Graph command. Thanks
Code:
import java.text.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class RungeKutta {
// class to create slider and window
private static File file1;
public static double A(double v, double x, double wc, double beta) {
return (-2 * beta * v - (Math.pow(wc, 2)) * Math.sin(x));
}
public static File getFile1() {
return file1;
}
public static void setFile1(File file1) {
RungeKutta.file1 = file1;
}
public static void main(String[] argv) throws IOException, ParseException {
createAndShowGUI();
}
private static void createAndShowGUI() {
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(14,1);
frame.setLayout(first);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow input from text field to be taken
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart and Button to take in Values for usage
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
class intakegui implements ActionListener
{
public intakegui()
{
BNewGraph.addActionListener((ActionListener) this);
BNewGraph.setActionCommand("Click to Draw");
}
#Override
public void actionPerformed(ActionEvent e) {
double l = Double.parseDouble(PLv.getText());
double xi = Double.parseDouble(ADv.getText());
double vi = Double.parseDouble(Avv.getText());
double dt = Double.parseDouble(TSv.getText());
double n = Double.parseDouble(MTv.getText());
double beta = Double.parseDouble(Vv.getText());
SimpleDateFormat dform = new SimpleDateFormat("ddMMyyyysmH");
Date d = Calendar.getInstance().getTime();
String dstr = dform.format(d);
String filename = ("result " + dstr + ".txt");
file1 = new File(filename);
PrintWriter savedValues = null;
try {
savedValues = new PrintWriter(filename);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//declare variable for gravity and omega*c
double g = 9.8;
double wc = Math.sqrt(g / l);
savedValues.println("#Initial Values Entered");
savedValues.println("#" + l + "," + vi + "," + xi + "," + dt + "," + n
+ "," + beta);
double[] dispTime = new double[(int) n];
double[] velTime = new double[(int) n];
// let a = angular acceleration
for (double j = 0; j < (int) n; j++) {
// int time = 1;
double k1v = dt * j * A(vi, xi, wc, beta);
double k1x = dt * j * vi;
double k2v = dt * j * A(vi, xi + (0.5 * k1x), wc, beta);
double k2x = dt * j * (vi + (0.5 * k1v));
double k3v = dt * j * A(vi, xi + (0.5 * k2x), wc, beta);
double k3x = dt * j * (vi + (0.5 * k2v));
double k4v = dt * j * A(vi, xi + k3x, wc, beta);
double k4x = dt * j * (vi + k3v);
xi += k1x / 6 + k2x / 3 + k3x / 3 + k4x / 6;
vi += k1v / 6 + k2v / 3 + k3v / 3 + k4v / 6;
dispTime[(int) j] = xi;
velTime[(int) j] = vi;
System.out.println(xi + "," + vi);
}
for (int i = 0; i < (int) n; i++) {
savedValues.println(dispTime[i] + " " + velTime[i]);
}
savedValues.close();
System.out.println("File saved. File name: " + filename);
}
}
}
}
You forgot to add listener to your button. You need to add listener as below:
BNewGraph.addActionListener(new intakegui());
Now when user clicks on button, you would see the file.

Lejos RGB color sensor

Does anyone have a code example of using the NXT RGB Color Sensor in the Lejos programming language. I have tried several different uses of setType() and setMode() but to no avail.
Here is some working code:
ColorLightSensor cs = new ColorLightSensor(SensorPort.S1, SensorConstants.TYPE_LIGHT_ACTIVE);
for(int i = 0; i < 100 && !done; i++)
{
cs.setFloodlight(lejos.robotics.Colors.Color.RED);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getRedComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.GREEN);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getGreenComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.BLUE);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getBlueComponent(), 0,0);
}
Here is a simple example for monitoring the NXT 2 color sensor:
import lejos.nxt.*;
import lejos.robotics.*;
public class MyColorSensor {
public static void main(String argv[]) {
ColorSensor cs = new ColorSensor(SensorPort.S1);
for(int i = 0; i < 10; i++) {
Color color = cs.getColor();
System.out.println("Color = " + cs.getColorID() + " " + color.getColor() +
"(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue()
+") " + color.getColor());
Button.waitForAnyPress();
}
}
}

Resources