Processing and arduino serial problem

Hi

I am trying to create a code that recieves data from a joystick connected to arduino using serial and move a red circle in the screen in the x direction only. However, the circle either does not move or a nullpointerexception or numberformatexception appears.
Here is the arduino code :

int jxPin = 0; // the analog pin for the x data
int x;

void setup() {
  Serial.begin(9600);

}

void loop() {
  x = map(analogRead(jxPin),0,1023,50,750);
  Serial.println(x);
  delay(100);
}

processing code :

import processing.serial.*;
Serial myPort;
int x;
int y = 401;
String val;
String xchar;
int l = 100;
int w = 100;

void setup() {
  size(800,800);
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  if (myPort.available() > 0) {
      xchar = myPort.readStringUntil('\n');
      if (xchar != null) {
          x = Integer.parseInt(xchar); // Here I always get the NumberFormatException
      }
  }
  background(x,y,255);
  fill(255,0,0);
  ellipse(x,y,l,w);
}

Processing code

import processing.serial.*;
Serial myPort;
int x;
int y = 401;
String inLine;
int l = 100;
int w = 100;

void setup() {
  size(800,800);
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
  myPort.bufferUntil('\n');
}

void draw() {
  background(x,y,255);
  fill(255,0,0);
  ellipse(x,y,l,w);
}

void serialEvent(Serial myPort) {
  inLine = myPort.readString();
  inLine = inLine.substring(0, inLine.length()-2);
  x = Integer.parseInt(inLine);
}

Thank you it works !

Could you please explain it briefly? I am interested on what was the issue before.

Use proper event handling and setup (bufferUntil / serialEvent), then parse the received line.

Serial handling is different in Processing, where draw runs at a predetermind rate
and not as fast as possible like loop on the Arduino.

And your "if something is available read its int value" is never a good strategy to read multi-byte values.

With the baud rate you use (why 9600?) you will get one character each millisecond,
and see all of them one at a time. '7' ...... '5' ...... '0' ...... CR ..... LF
Maybe the CR and LF chars throw the conversion exception.