Unexpected symbol Error for my Int varible - unexpected-token

using System;
using static System.Console;
using System.Globalization;
class MoveEstimator
{
static void Main()
{
string entry;
int base;
base = 200;
int rph = 150;
int rpm = 2;
int input;
int hours;
int miles;
int total;
WriteLine ("Enter number of hours for job >>");
entry = ReadLine ();
WriteLine ("Enter number of miles for job >>");
string entryii = ReadLine ();
hours = Convert.ToInt32(entry);
miles = Convert.ToInt32(entryii);
total = (base + rph*hours + rpm*miles);
WriteLine ("For a move taking{0} hours and going {1}miles the estimate is {2}",hours,miles,total.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
}
I keep getting a error saying that my integer variable "base" is a unexpected symbol. all i did is say int base;. how its that wrong. I am also getting a error for every time I reference it.

First of all, welcome to the Stack Overflow!
base is a reserved keyword in C#, so you should give this variable any other name, for example initialDistance))

Related

Function to calculate absolute value of given numbers

complete newbie here. I need help making two functions abs1 and abs2, in order to calculate the absolute value of the numbers -2 and -7, and print them out so it displays 27. However i don't want to change the existing loop i made, i want to add the functions separately. This is being coded on an Arduino.
This is the code i have written so far:
void setup() {
Serial.begin(9600)
}
void loop() {
int number1 = -2;
int number2 = -7;
number1 = abs1(number1);
abs2(&number2);
Serial.print(number1);
Serial.print(number2);
}
I have tried to use int abs1=abs(number1), but it only gives the error messages"number1 was not declared" or "abs1 was not declared" or " Failed to compile for Arduino Genuino Mega 2560" depending on where I place the line.
Why do you think you need two functions? Why not use the regular old abs function?
void loop() {
int number1 = -2;
int number2 = -7;
number1 = abs(number1);
number2 = abs(number2);
Serial.print(number1);
Serial.print(number2);
}
If you just need to print the absolute values just use the abs function at serial print.
void loop() {
int number1 = -2;
int number2 = -7;
Serial.print(abs(number1));
Serial.print(abs(number2));
}

How to fix Exception in thread "main" java.lang.NullPointerException

I have this error when I Run the code but no when I Compile it.
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(StringTokenizer.java:199)
at java.util.StringTokenizer.<init>(StringTokenizer.java:221)
at WillinsLaMarkusFileInputOutput.main(WillinsLaMarkusFileInputOutput.java:23)
Here is my complete code
import java.io.*;
public class WillinsLaMarkusFileInputOutput {
public static void main(String[] args) throws IOException {
/* open the files */
// Scanner sc = new Scanner(System.in);
BufferedReader r = new BufferedReader(new FileReader("input.txt"));
BufferedWriter w = new BufferedWriter(new FileWriter("output.txt"));
float[] values = new float[10];
String str = r.readLine();
int i = 0;
float sum = 0.0f, avg = 0.0f;
/* tokenize the string into floats separated by spaces */
java.util.StringTokenizer tk = new java.util.StringTokenizer(str, " ");
while (tk.hasMoreElements()) {
values[i] = Float.valueOf(tk.nextToken()).floatValue();
/* compute sum */
sum += values[i];
i++;
}
/* calculate average */
avg = sum / 10.0f;
/* write results to output.txt */
w.write("Sum: " + sum);
w.newLine();
w.write("Average: " + avg);
w.flush();
/* close the files */
r.close();
w.close();
}
}
Any suggestions on how to fix this ?
The exception goes from this line:
java.util.StringTokenizer tk = new java.util.StringTokenizer(str, " ");
So first let's read the documentation when this constructor may throw NullPointerException:
public StringTokenizer(String str, String delim)
Throws:
NullPointerException - if str is null
Fine. It means that str is null. The str is assigned in this line:
String str = r.readLine();
Now you should read the documentation when r.readLine() may return null:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So it signals that end of file is reached. As it's the very first attempt to read something from this file it seems that you are reading an empty file.
In general careful documentation reading may greatly help to understand why your program doesn't work.

Sending JSON data (Twitter (Temboo)) from Processing to Arduino

I'm working on a student project and trying to send JSON data (based on the twitter hashtag '#tune') from Processing to Arduino, but the method 'myPort.write(status);' isn't usable with JSON, I've looked around online but not sure what command to use - Am I on the right track? Here's the code:
Processing:
import processing.serial.*; //Serial connection for Arduino
import java.lang.reflect.Method;
import com.temboo.core.*; // Temboo library
import com.temboo.Library.Twitter.Search.*; // Temboo Twitter search library
// Create a session using your Temboo account application details
TembooSession session = new TembooSession("MYUSERNAME", "MYTEMBOOAPPNAME", "MYTEMBOOCODE");
// Setup objects
Serial myPort; // Create object from Serial class
int portNo = 7; // Define portNo as int
int baudRate = 9600; // Define baudRate as int
void setup() {
// Run the Tweets Choreo function
runTweetsChoreo();
String portName = Serial.list()[portNo]; // Setup String for port ([7] is the port number for my machine)
myPort = new Serial(this, portName, baudRate); // Setting up serial port
}
void runTweetsChoreo() {
// Create the Choreo object using your Temboo session
Tweets tweetsChoreo = new Tweets(session);
// Set credential
tweetsChoreo.setCredential("ArduinoUkulele");
// Set inputs
// Run the Choreo and store the results
TweetsResultSet tweetsResults = tweetsChoreo.run();
// retrieve the results as JSON
JSONObject results = parseJSONObject(tweetsResults.getResponse());
// retrieve the statuses from the results
JSONArray statuses = results.getJSONArray("statuses");
// loop through the statuses
for (int i = 0; i < statuses.size(); i++){
JSONObject status = statuses.getJSONObject(i);
println(status.getString("text"));
println(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- ");
myPort.write(status); // THIS IS THE CODE NOT WORKING WITH JSON
}
}
Arduino:
char val; // Data received from the serial port
int ledPin = 13; // Set the pin to digital I/O 13
void setup(){
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop(){
if (Serial.available()) { // If data is available to read,
val = Serial.read(); // read it and store it in val
Serial.println(val);
delay(10); // Wait 10 milliseconds for next reading
}
}
I'm sure I'm just looking for a certain command - once I've received the data I'm just looking to turn the LED on based on a new hashtag being receieved. Any help would be greatly appreciated!
Cheers
Arthur
write() method cannot take JSONObject as input, only byte[], String. But you already have everything you need: just use getString() method as you are doing it two lines above (using appropriate key string, which you should know from API that you are using on top of JSON):
myPort.write(status.getString("text"));

How to adress elements of a recursive function?

Take a recursive function, say:
public static long rekurs(long n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 1;
} else {
return rekurs(n - 1)*(rekurs(n - 2)+4;
}
}
When n=20, the function has to find all the values S(n) for n=2,...,19 first.
When I let n go from 20 to 21, it does the same thing again (plus finding S(20)).
Now I want to create an array, in which the found values S(n) for n=2,...,19 are filled into, so that the function for n=21 does not have to do the same thing again, but how do I get those elements?
This is the solution I figured out, it's a little bit different from the lecture example.
The keyword that helped me is "dynamic programming".
import java.util.Arrays;
public class Bsp13 {
public static final int N = 0;
public static final int Ende = 20;
public static long[] schroe = new long[N + Ende + 1];
public static void main(String[] args) {
schroe[0] = 1;
schroe[1] = 1;
for (int n = 2; n <= Ende + N; n++) {
schroe[n] = ((6 * n - 3) * (schroe[n-1]) - (n - 2) * (schroe[n-2])) / (n + 1);
}
System.out.println(schroe[N]);
System.out.println(Arrays.toString(schroe));
System.out.println(schroe[N+Ende]);
}
}
What you are trying to do is called dynamic programming. Basically it is bookkeeping in order to not compute subsolutions more than once.
So basically, you need a mapping of n values to solution values. I would suggest you use a dictionary-like-datastructure for this task.
When a value for n needs to be computed, you first check whether the solution is in the dictionary, if yes you return the result. If not, you compute the result and put it into the dictionary.
Think about how you would initialize this dictionary and how you would pass it down to the recursive function calls.
Here's a lecture video on dynamic programming where the computation of Fibonnaci-numbers using dynamic programming is explained, which is very similar to what you are trying to do:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-19-dynamic-programming-i-fibonacci-shortest-paths/

AS3: Optimizing Object Memory Size

I have have a class that I wrote, and it seems bigger than it should be. It doesn't extend anything, and has very little going on - or so I thought - but each one is taking up just under 100k100 bytes ( thanks back2dos ). I guess that I don't have a very good understanding of what really affects how much memory an object takes up in AS3.
If anyone can point me to some reading on the subject that might be helpful, or perhaps explain some insight into how to think about this, that would be awesome.
I would like to keep a LOT of these objects in memory - and I thought I could until now, but at this size I'm going to have to create them or use an object pooling technique of some kind.
Thanks for the assistance.
Edit: Although I've got this in order, I'm keeping the code I posted here for completeness. The class has been heavily modified from the original version. Values that were referencing other files have been made static as to allow the code to run for someone else ( in theory hehehe... ).
Although my situation is sorted out, I'll give the answer to a good reference for information on classes and memory.
In this case the class has 15 variables. I'm only using a single String and a bunch of ints, Numbers, and Booleans with some references to more of the same in globally available XML data. It also imports Point for the constructor, though no points are stored. In testing, even without the global XML references or Point class it's still around a ~84k each. There are getters for 7 of the variables and a couple methods in addition to the constructor. All of which are less than 20 lines ( and I have a very sparse coding style ).
The class mentioned for reference, but feel free to generalize:
package
{
public class AObject
{
private var _counter:int;
private var _frames:int;
private var _speed:int;
private var _currentState:String;
private var _currentFrame:int;
private var _offset:int;
private var _endFrame:int;
private var _type:int;
private var _object:int;
private var _state:int;
private var _x:Number;
private var _y:Number;
private var _w:int;
private var _h:int;
private var _update:Boolean;
public function AObject( targetX : int, targetY : int, state : int, object : int, type : int )
{
_x = targetX;
_y = targetY;
_type = type;
_object = object;
_state = state;
_counter = 0;
_w = 32;
_h = 32
_update = true;
setState( state );
}
public function setState( state:int ) : void
{
_currentState = "bob";
var frameCounter : int = 0;
var stateCounter : int = state - 1;
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
_offset = frameCounter;
_currentFrame = _offset;
_speed = 10;
_frames = 4;
_endFrame = _offset + _frames - 1;
}
public function get state() : int
{
return _state;
}
public function animate() : Boolean
{
if ( count() )
{
if( _currentFrame < _endFrame )
{
++_currentFrame;
}
else
{
_currentFrame = _offset;
}
_speed = 10;
return true;
}
else
{
return false;
}
}
private var adder: Number = 0;
private function count():Boolean
{
_counter++;
if ( _counter == _speed )
{
_counter = 0;
return true;
}
else
{
return false;
}
}
public function get x():int
{
return _x;
}
public function get y():int
{
return _y;
}
public function get type():int
{
return _type;
}
public function get object():int
{
return _object;
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get w():int
{
return _w;
}
public function get h():int
{
return _h;
}
}
}
i am amazed, this compiles at all ... when i try to compile it with the flex SDK, it creates an enormous collision with the built-in class Object, which is the base class of any class, making my trace output overflow ...
other than that, this is an infinite loop if you pass a value for state bigger than 0
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
but it seems really strange these objects are so big ... after renaming and taking care not to pass in 0 for the state, i ran a test:
package {
import flash.display.Sprite;
import flash.sampler.getSize;
import flash.system.System;
public class Main extends Sprite {
public function Main():void {
const count:int = 100000;
var start:uint = System.totalMemory;
var a:Array = [];
for (var i:int = 0; i < count; i++) {
a.push(new MyObject(1, 2, 0, 4, 5));
}
var mem:uint = System.totalMemory - start - getSize(a);
trace("total of "+mem+" B for "+count+" objects, aprox. avg. size per object: "+(mem/count));
}
}
}
it yields:
total of 10982744 B for 100000 objects, aprox. avg. size per object: 109.82744
so that's quite ok ... i think the actual size should be 4 (for the bool) + 4 * 11 (for the ints) + 4 (for the reference to the string) + 8 * 3 (for the three floats (you have the adder somewhere over the count) + 8 for an empty class (reference to the traits objects + something else), giving you a total of 88 bytes ... which is, what you get, if you getSize the object ... please note however, that getSize will only give you the size of the object itself (as calculated here) ignoring the size of what strings or other objects your object references ...
so yeah, apart from that name you definitely should change, the problem must be somewhere else ...
greetz
back2dos
If you really want to save on space, you can fake shorts by using unsigned integers, and using upper/lower bits for one thing or another.
ints are 4 bytes by nature, you can reuse that int on anything less than 2^8.
width height
0xFFFF + 0xFFFF
offset endframe
0xFFFF + 0xFFFF
This though gets ugly when you want to write anything or read anything, as to write width or height you'd have to:
writing:
size = (width & 0x0000FFFF) << 16 | (height & 0x0000FFFF);
reading:
get width():uint { return (size & 0xFFFF0000) >> 16 };
That's ugly. Since you're using getters anyways, and assuming computation speed is not an issue, you could use internal byte arrays which could give you even more granularity for how you want to store your information. Assuming your strings are more than 4 bytes, makes more sense to use a number rather than a string.
Also, I believe you will actually get some memory increase by declaring the class as final, as I believe final functions get placed into the traits object, rather than