What is the bug in this Java programm? - catch-block

The compiler is not executing the catch part when no value is entered:
import java.util.Scanner;
import java.lang.*;
public class Ruff {
public static void main(String[] args)
{
String a;
Scanner scanf=new Scanner(System.in);
System.out.println("Enter your name!!");
a=scanf.nextLine();
try
{
if(a.toLowerCase().equals("Harsh"))
{
System.out.print("Good Name");
}
else
{
System.out.print("Ok!");
}
}
catch(Exception e)
{
System.out.print("Name Required");
}
}
}

The only possible exception for a in the code is a NullpointerException, but a is the empty string not a null pointer If the user enters no value. You should check for that value instead of using exceptions:
if(a.equals("")) {
System.out.print("Name Required");
}
else {
// code of try block here ...
}

Related

Fixing setCellFactory in javafx

I have problem with to set a setCellFactory column.
My code looks like this:
#FXML
private void EditStudentMarkAction(Integer idUser){
ObjectMapper mapper = new ObjectMapper();
List<Marks> lista = null;
String path = "http://localhost:8080/Server/source/users/"+idUser+"/marks";
try {
lista = mapper.readValue(new URL(path), new TypeReference<List<Marks>>(){});
} catch (IOException ex) {
System.out.println(ex);
}
ObservableList<Marks> lis = FXCollections.observableArrayList(lista);
columnFirst.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getTest().getTitle()));
columnSecond.setCellValueFactory(new PropertyValueFactory<Marks,String>("date"));
columnThird.setEditable(true);
columnThird.setCellValueFactory(new PropertyValueFactory<Marks,String>("mark"));
columnThird.setCellFactory(TextFieldTableCell.forTableColumn());
columnThird.setOnEditCommit(
new EventHandler<CellEditEvent<Marks, String>>() {
#Override
public void handle(CellEditEvent<Marks, String> t) {
((Marks) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setMark(Float.parseFloat(t.getNewValue()));
}
}
);
tableEdit.getColumns().setAll(columnFirst,columnSecond,columnThird);
tableEdit.setItems(lis);
}
Error:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.String
When I comments line:
columnThird.setCellFactory(TextFieldTableCell.forTableColumn());
That's my code works, but I can't to edit a row.
So I must translate Float to String in method setCellFactory something like this Stack yes? but I must change Integer to Float?
I added the following code, but still no work and do not build program:
columnThird.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<Float>() {
#Override
public String toString(Float t) {
return t.toString();
}
#Override
public Float fromString(String string) {
return Float.parseFloat(string);
}
}));

Java - Exception PropertyUtilsBean.setIndexedProperty

public class TestBean {
private String[] array;
public String[] getArray() {
return array;
}
public void setArray(String[] array) {
this.array = array;
}
}
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilTest {
public static void main(String[] args) {
TestBean bean = new TestBean();
try {
BeanUtils.setProperty(bean, "array[0]", "zero");
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
While running the code the following exception is getting
java.lang.NullPointerException
at org.apache.commons.beanutils.PropertyUtilsBean.setIndexedProperty(PropertyUtilsBean.java:1414)
at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1016)
at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313)
at BeanUtilTest.main(BeanUtilTest.java:10)
The array size will be increase while run time. So I don't want as a fixed size array. Array size should be defined at runtime.
You need to initialize the array or set the array using
BeanUtils.setProperty(bean, "array", array);
and then use following operation to set the value
BeanUtils.setProperty(bean, "array[0]", "zero");
Array size will not increase during runtime

Doing Back Ground AsyncTask

I Am Trying to load a dynamic URL for Mediaplayer. How to handle various kinds of exceptions like file not found & timeout Exceptions that arise during execution.
public class MediaAsynchTask extends AsyncTask<String, Void, Object> {
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(AudioView.this);
progress.setMessage("LOADING........");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
progress.show();
}
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if(result!=null){
progress.dismiss();
}else{
Audio.this.finish();
}
}
Protected Object doInBackground(String... params) {
try {
if (!true)
{
MediaPlayer m = MediaPlayer.create(Audio.this,Uri.parse("audiourl.mp3"));
myProgressBar.setMax(mMediaPlayer.getDuration());
}return mMediaPlayer;
}catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Check Your NetWork and Data Connection",Toast.LENGTH_LONG).show();
}
});
}
return mMediaPlayer;
}
}
its very simple you can do it like this:
try{
**//your code goes here**
}catch(FileNotFoundException exception){
//handle exception
}//**handle other possible exceptions**
catch(JsonParseException exception){
exception.printStackTrace();
}catch(JsonProcessingException exception){
exception.printStackTrace();
}

How to login into Salesforce application using selenium webdriver?

public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver = driver;
}
public void loginAs(String username, String password)
{
/* driver.get("https://login.salesforce.com/?locale=uk");
driver.manage().timeouts().implicitlyWait(05, TimeUnit.SECONDS);
System.out.println("READ");
// System.out.println(driver.findElement(By.id("pwcaps")).getText());
//driver.findElement(By.id(username)).sendKeys("sambit");
//driver.findElement(By.className(password)).sendKeys("PWD");
//driver.findElement(By.id(username)).sendKeys("Password");
/*if (driver.findElement(By.className("loginButton")).isEnabled())
{
System.out.println("entered If loop");
System.out.println("login Button is enabled");
driver.findElement(By.className("loginButton")).click();
}
else
{
driver.close();
}*/
if (driver.findElement(By.id("Account_Tab")).isEnabled())
{
System.out.println("Account tab is enabled");
}
else
{
System.out.println("Account tab is not enabled");
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
LoginPage login = new LoginPage(new InternetExplorerDriver());
login.loginAs("sambit.sabyasachi", "check");
}
The webpage shows that this field does not enable automatic filling of the form
Please check this code it work fine for me
public class login
{
public static void main(String[] args)
{
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver iedriver = new InternetExplorerDriver(ieCapabilities);
iedriver.get("https://login.salesforce.com/?locale=uk");
try {
Thread.sleep(4000);
} catch (Exception e) {
// TODO: handle exception
}
driver.findElement(By.id("username")).sendKeys("username");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("Login")).click();
}
}
try the following login function.
public void login(String username, String password){
driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.cssSelector("input[type='password']")).sendKeys(password);
driver.findElement(By.cssSelector("input[type='submit']")).click();
}
I am not sure what your intentions are once you are logged in, but this works for us for our salesforce based application testing.
You would call this function after loading up the login page.

Excpetion Handling with a NativeAcitivity

I'm using a NativeActivity with a child activity called Body and a ActivityAction called OnFault, this is my code:
[Designer(typeof(RetryDesigner))]
public sealed class Retry : NativeActivity {
public Activity Body { get; set; }
public ActivityAction<Exception> OnFault { get; set; }
protected override void CacheMetadata(NativeActivityMetadata metadata) {
metadata.AddChild(Body);
metadata.AddDelegate(OnFault);
base.CacheMetadata(metadata);
}
protected override void Execute(NativeActivityContext context) {
context.ScheduleActivity(Body, OnBodyCompleted, OnBodyFaulted);
}
void OnFaultCompleted(NativeActivityContext context, ActivityInstance instance) {
context.ScheduleActivity(Body);
}
void OnBodyCompleted(NativeActivityContext context, ActivityInstance instance) {
}
void OnBodyFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom) {
faultContext.HandleFault();
if (OnFault != null) {
faultContext.ScheduleAction<Exception>(OnFault, propagatedException, OnFaultCompleted);
}
}
}
and my main looks like this:
static void Main(string[] args) {
Variable<Exception> ex = new Variable<Exception>();
DelegateInArgument<Exception> exception = new DelegateInArgument<Exception>();
Retry retry = new Retry {
Body = new Sequence {
Variables = { ex },
Activities = {
new Assign<Exception> {
To = new OutArgument<Exception>(ex),
Value = new InArgument<Exception>((env) => new Exception("test"))
},
new Throw {
Exception = ex
}
}
},
OnFault = new ActivityAction<Exception> {
Argument = exception,
Handler = new Sequence {
Activities = {
new WriteLine{
Text = new InArgument<string>(env =>
exception.Get(env).Message)
}
}
}
}
};
var workflow = new WorkflowInvoker(retry);
workflow.Invoke();
Console.WriteLine();
}
The problem is that the exception don't stop in the OnBodyFaulted callback and appear on the main as an unhedled expetion.
How can I stop the Exception inside the OnBodyFault callback, is there any state or property on the workflow to do that?
The problem is that in the OnFaultCompleted() you are calling context.ScheduleActivity(Body) again. This time without a fault handler so that causes the same fault to occur again and the complete workflow to fault.

Resources