How To Use Scanner Inside a Method - java.util.scanner

I am trying to use Scanner inside a method to read the value of a string that I am converting to an int. The method is inside a class, which is an object created by the class holding main.
Some psuedocode:
class Project1 {
main() {
Circle c = new Circle();
c.createCircle();
}
}
Now the class holding the scanner:
'''
public class Circle {
public int radius = 0;
public int createCircle() throws IOException {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter the radius:");
try {
radius = Integer.parseInt(sc1.nextLine());
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Please enter a number.");
} finally {
sc1.close();
}
System.out.println("The radius is: " + radius);
return radius;
}}
'''
Running this code returns the error: Exception in thread "main" java.util.NoSuchElementException: No line found.
It is thrown by the "radius = Integer.parseInt(sc1enter code here.nextLine());" line.
Thank you for any help!
Chuck

I figured it out, because I was also using scanner in my main method in the Project1 class, and closing that Scanner, I was closing Scanner across the whole application, and once closed, it seems it cannot be reopened, so I have commented out the code closing the scanner and will move that some place to where it will close with the whole application

Related

NullReferenceException Fire Ball

I'm working on this game breakout-game
And i'm trying to make the ball fire and collide with the wall bouncing, to do that I did what he said, I added a script and put this code:
public class BallMove : MonoBehaviour {
private Rigidbody rb;
public float ballVelocity = 800f;
private bool isMove;
// Use this for initialization
void awake() {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1") && isMove == false) {
transform.parent = null;
isMove = true;
rb.isKinematic = false;
rb.AddForce (new Vector3(ballVelocity,ballVelocity,0));
}
}
}
I understand every line of this code, but when I try to play this, I got a nullReferenceException ,I can run the game but when I press the key I'm getting a error,someone know why? and what happens?
You should use Awake(), not awake(). In your case, you are using a "customized" function, and not the "official" one used by the Unity engine.
So, the engine cannot start that function by itself, and rb stills null when used in the Update().
Example:
void Awake() {
rb = GetComponent<Rigidbody> ();
}

Adding gauge in location finder class in j2me

I am working on a j2me application which contain a class to find the location of mobile using GPS.I need to include gauge while the location provider API is called and it finds the location.I am new to j2me so still not clear with all the concepts.I am pasting my code below.Please help me through this.Thanks in advance..
package org.ets.utils;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;
import javax.microedition.io.*;
import java.io.*;
import org.ets.midlet.ETS_infozech;
import javax.microedition.midlet.*;
public class Locfinder {
public Locfinder(ETS_infozech midlet)
{
this.midlet = midlet;
}
public static String ex()
{
try {
checkLocation();
} catch (Exception ex)
{
ex.printStackTrace();
}
//System.out.println(string);
return string;
}
public static void checkLocation() throws Exception
{
Location l;
LocationProvider lp;
Coordinates c;
// Set criteria for selecting a location provider:
// accurate to 500 meters horizontally
Criteria cr= new Criteria();
cr.setHorizontalAccuracy(500);
// Get an instance of the provider
lp= LocationProvider.getInstance(cr);
//Request the location, setting a one-minute timeout
l = lp.getLocation(60);
c = l.getQualifiedCoordinates();
if(c != null ) {
// Use coordinate information
double lat = c.getLatitude();
double lon = c.getLongitude();
string = " LAT-" + lat + " LONG-" + lon;
}
}
}
There's no way you can link a Gauge to some task.
You have to set values to the Gauge manually. So you'd create a Gauge and add it to your Form. Then start your code to perform the look-up.
In between your lines of code, you'd add myGauge.setValue(some_value); to increase the indicator.
Of course, this becomes difficult when most of the task is contained in a single line of code, like e.g. lp.getLocation(60);.
I think, in that case, I would create a Thread that automatically increases the value on the Gauge in the 60 seconds, but can be stopped/overridden by a manual setting.
class Autoincrementer implements Runnable {
private boolean running;
private Gauge gauge;
private int seconds;
private int secondsElapsed;
public Autoincrementer(Gauge gauge) {
this.gauge = gauge;
this.seconds = gauge.getMaxValue();
this.running = true;
this.secondsElapsed = 0;
}
public void run() {
if (running) {
secondsElapsed++;
gauge.setValue(secondsElapsed);
if (secondsElapsed>=gauge.getMaxValue()) running = false; // Stop the auto incrementing
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (Exception e) {}
}
}
public void stop() {
running = false;
}
}
You would then create a Gauge and add it to your Form
myGauge = new Gauge("Process", false, 60, 0);
myForm.append(myGauge);
Then start the auto-increment.
myIncrementer = new Autoincrementer(myGauge);
new Thread(myIncrementer).start();
And then call your look-up code.
checkLocation();
Inside your look-up code, add code to stop the auto-incrementing and set the Gauge object to 100%, if the look-up was successful (meaning before the timeout).
myIncrementer.stop();
myGauge.setValue(60);
LWUIT 1.5 can help you in this. Am not sure for Location API which you are using.
But you will get Gauge using LWUIT 1.5. Use Lwuit instead of LCDUI.
http://www.oracle.com/technetwork/java/javame/javamobile/download/lwuit/index.html

use thread inside buttonclick in android

I am receiving temperature values from a sensor through BLE and storing it in my db and passing the values as an array through intent to graph activity and diplaying a line graph. I am also posting the values to google app engine. i am doing this all within runOnUiThread() and hence my app crashes when there are too many values.Is it possible to pass values into the graph activity on a new thread? or any other better suggestions?
#Override
public void propertyChange(final PropertyChangeEvent event) {
final String property = event.getPropertyName();
runOnUiThread(new Runnable() {
public void run() {
try {
if (property.equals(PROPERTY_IR_TEMPERATURE)) {
double newIRValue = (Double) event.getNewValue();
// float newIRValue_1 = (Float) event.getNewValue();
TextView textView = (TextView) findViewById(R.id.ir_temperature);
String value = decimal.format(newIRValue);
String formattedText = value + DEGREE_SYM;
float value_chk = (float)(newIRValue);
String formattedText_1 = String.valueOf(value_chk);
String sensorid = test_1;
String sensortype = "temperature";
// write_data(sensorid,sensortype,value);
// Toast.makeText(getBaseContext(), "ARV sensid:"+sensorid+" senstype:"+sensortype, Toast.LENGTH_SHORT).show();
long timemilli = System.currentTimeMillis();
//Log.d("TIMMEE", String.valueOf(timemilli));
String time=String.valueOf(timemilli);
db = new DBHandler(getApplicationContext());
//db.deleteTempReadings();
// inserting data to temp table
Log.i("insert", "Inserting Records...");
);
Temperature(sensorid,formattedText_1));
//Toast.makeText(getBaseContext(), "SENSOR_ID:"+t.getSensorId()+"TEMPERATURE: "+t.getTemperature()+"TIME: "+t.getTimestamp(), Toast.LENGTH_LONG).show();
// reading data from db
Log.i("Reading", "Reading Records...");
List<Temperature> temp = db.getAllTempReadings();
int arraySize=temp.size();
double tempArray[]=new double[arraySize];
int timeArray[]=new int [arraySize];
//Log.d("ans", String.valueOf(temp.size()));
for (Temperature t : temp) {
String log="SENSOR ID: "+t.getSensorId()+"TEMPERATURE: "+t.getTemperature()+"TIME: "+t.getTimestamp();
Log.d("Record"+t, log);
}
// Reading values into the array!
for(int i=0;i<arraySize;i++){
tempArray[i]=Double.parseDouble(temp.get(i).getTemperature());
}
Button btn=(Button)findViewBy Id(R.id.btnGraph);
btn.setOnCLickListener(new View.onClickListener(){
public void onClick(View v){
Intent iIntent =new Intent(getApplicationContext(),GraphActivity.class);
tIntent.putExtra("tempArray",tempArray);
startActivity(tIntent);
}
});
// rest....posting to server code......
textView.setText(formattedText);
}
}
}
}
}
The temperature value you get from the sensor upto this you have to do stuff in one thread and after that you have to start three thread one for the inserting into the DB, the other one for the displaying the line graph and the last and the third one for the posting the data into the google app engine.
I think you are a bit confused here. The idea is to keep slow processing OUT of your UI thread. I suggest you do the writes to the DB and the App engine first in the 'current' (presumably less critical) thread and then when all is done simply update the graph display in the UI thread.
The only reason you need RunOnUiThread is to make changes to the views on the screen.

Replace Text with number in TextField

I have this field in which I insert port number. I would like to convert the string automatically into number:
fieldNport = new TextField();
fieldNport.setPrefSize(180, 24);
fieldNport.setFont(Font.font("Tahoma", 11));
grid.add(fieldNport, 1, 1);
Can you tell how I can do this? I cannot find suitable example in stack overflow.
EDIT:
Maybe this:
fieldNport.textProperty().addListener(new ChangeListener()
{
#Override
public void changed(ObservableValue o, Object oldVal, Object newVal)
{
try
{
int Nport = Integer.parseInt((String) oldVal);
}
catch (NumberFormatException e)
{
}
}
});
Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:
UnaryOperator<Change> filter = change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);
This avoids both subclassing and duplicate change events that you will get when you add a change listener to the text property and modify the text in that listener.
You can write something like this :
fieldNPort.text.addListener(new ChangeListener(){
#Override public void changed(ObservableValue o,Object oldVal, Object newVal){
//Some Code
//Here you can use Integer.parseInt methods inside a try/catch
//because parseInt throws Exceptions
}
});
Here are all the things you'd need about properties and Listeners in JavaFX:
http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm
If you have any question, I'll be glad to help.
Maybe this is what you need:
fieldNPort= new TextField()
{
#Override
public void replaceText(int start, int end, String text)
{
if (text.matches("[0-9]*"))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (text.matches("[0-9]*"))
{
super.replaceSelection(text);
}
}
};
This will restrict the users from entering anything but numbers(you can modify the regex expression to your needs) and then you do not have to worry about Integer.parseInt throwing any exception.

Blackberry Thread Image from JSON

I am looking for a way to display images on my ListField from a background thread. First in my drawListRow i try this
path = (String) imagePaths.elementAt(index);
bit = connectServerForImage(path);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
but can't scroll smoothly throughout the list, and they say do not do networking or other blocking operations on the UI. But i also try this
private class imgConnection extends Thread
{
public imgConnection() {
super();
}
public void run() {
try {
for (int i = 0; i < imagePaths.size(); i++)
{
final int index = i;
String path = imagePaths.elementAt(index).toString();
bit = connectServerForImage(path);
image.addElement(bit);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(image.size());
subManager.add(_list);
screen.invalidate();
}
});
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
bit = (Bitmap) image.elementAt(index);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
}
but nothing happens. Any idea, comments.
You are right, i just started java development 2 weeks ago particularly BB development and i try this link. I want to add a background thread to download image after i got the path url from json return.
first thread:
_connectionthread = new Connection();
_connectionthread.start();
private class Connection extends Thread
{
public Connection()
{
super();
}
public void run() {
try {}
catch (Exception e) {}
}
}
second thread:
_imgConnectionThread = new ImgConnection();
_imgConnectionThread.start();
private class ImgConnection extends Thread
{
public ImgConnection() {
super();
}
public void run() {
try {
}
catch (Exception e)
{
}
}
}
how to update images on ListField?
Answer is based on code from - pastebin.com/90UKTHzP
Terrible code! It's really hard to read and undersand! It looks like you copy pasted several examples from different locations. Also you overriding default behavior with same behavior. Also MainScreen already has VerticalManagerField. Also you're adding list every iteration to manager which will cause IAE. And main one thread is depended on result of second one. They start at the same time, but getting json from server and it's processing could take longer time, so image thread most probably will finish his run without any result.
So main recommendation to fix it - read clean code book! Read more about java development - conventions, multithreading. Read about BB development - UI api, networking.
And finally - start only one thread to get and parse json. After you get it finished - start another thread to get images.
There some minor things that could save you more battery and processor time also - start loading images on demand - when it painted or going to be painted (user scrolls list).
By convention, Java class names start with a capital letter, so imgConnection should really be ImgConnection.
In your sample code, I don't see imgConnection being instantiated anywhere, and I don't see any call to Thread.start(), which is the way a thread i started. Without Thread.start() it is not surprising nothing is happening - the thread is never starting.

Resources