BlueJ User Input Code Never Compiles - input

I have a small piece of code that should compile and allow the user to input a figure in the terminal window ( I am using Blue J).
However, while it does 'compile', I can never open, view or interact with the terminal window. I am met with a red "object box" instead.
I have been trying for a while to get around this problem and I can't seem to find the answer anywhere.
Here is the code used:
import java.util.Scanner;
public class PartA
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input your message: "); //this is the user promot
String message = input.nextLine();
System.out.println(message);
}
}

I've figured out the answer to this problem since posting.
While I was clicking on new PartA() to view the program in the terminal window, this only created an object (the red box). By clicking on public static void main(String[] args) (essentially a method as opposed to an object) I was able to view, and interact with the terminal window.

Related

Execute a simple java code in Intellij-Idea

Can you help me to run the code? I am trying to execute the following:
public class HelloWorld {
public static void main (String[] args) {
System.out.println("Hello,world!");
}
}
To do that I click Run->Run (the second one with Alt+Shift+F10). It outputs a small window where the only available option is Edit configurations, I tried to do that but with no success.
While editing your first configuration.
Clik + button and choose Application template
In Main class: type HelloWorld or pick it from the picker ...

Selenium.StaleElementReferenceException on action.SendKeys after following link?

I am having some issues using selenium, and specifically using actions, although this could just be a symptom for a bigger issue. To quickly explain what try to do:
I scroll down to the bottom of a page using SendKeys(Keys.ArrowDown)
I press a button, and I change the page to a different language.
I try to scroll down on the new page using SendKeys(Keys.ArrowDown). This is where i receive an error!
The strange thing here is that i have no issues with the scrolling in step 1 even though I am using the same function, but in step 3 i receive an error message:
OpenQA.Selenium.StaleElementReferenceException: 'The element reference of is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed'
I have tried to redeclare my footer variable, and also included it as a Footer class variable (originally it wasn't), but nothing i do change anything
The reason I am using SendKeys and not MoveToElement is due to MoveToElement doesn't work for off-screen elements in Firefox. I have included all relevant code below, including an image of the error and when it happens.
Could anyone please advice what I am doing wrong?
[TestMethod]
public void Reset_newsletter_subscription_form_BR_site()
{
Browser.Goto(siteUrl);
Webpage.Footer.GoTo_CountryPageViaFooter("br");
Webpage.Footer.ScrollToFooter(); // -> This is where it fails!
Other.Irrelevant.Stuff();
}
Below this is the Selenium parts:
public static class Browser
{
public static IWebDriver webDriver;
public static Actions actions;
public static void Goto(string url)
{
webDriver.Url = url;
}
}
public static class Webpage
{
public static Footer Footer
{
get
{
var footer = new Footer(Browser.webDriver, Browser.actions);
return footer;
}
}
}
public class Footer
{
private IWebDriver webDriver;
private Actions actions;
private IWebElement footer;
public Footer(IWebDriver webDriver, Actions actions)
{
this.webDriver = webDriver;
this.actions = actions;
}
public void GoTo_CountryPageViaFooter(string CountryTag)
{
footer = webDriver.FindElement(By.ClassName("c-footer"));
var changeCountryButton = footer.FindElement(By.ClassName("c-footer__toggle-country-selector"));
ScrollToFooter();
actions.MoveToElement(footer).Perform();
actions.MoveToElement(changeCountryButton).Perform();
changeCountryButton.Click();
var intPageLink = footer.FindElement(By.XPath("//*[#href='/" + CountryTag + "/']"));
intPageLink.Click();
}
public void ScrollToFooter()
{
footer = webDriver.FindElement(By.ClassName("c-footer"));
//MoveToElement does not work for Firefox, so a workaround is needed.
if (webDriver is FirefoxDriver)
{
int i = 0;
while (i < 5)
{
actions.SendKeys(Keys.ArrowDown).Perform(); //This is where it fails!
i++;
}
}
actions.MoveToElement(footer).Perform();
}
Image of the exception
Whenever Perform() method is invoked, it figures how to interact with the Page. So its job is to find out the active element present in the Page(if element not specified as in MoveToElement(element) or during clicking an element using Actions).
So in your case, as no Element is specified actions.SendKeys(Keys.ArrowDown).Perform(); so Actions will focus on any Active Element present in the Page and Perform the SendKeys Operation on that.
Details about Actions Interaction with Web Page..
So, as soon as the Language change link is getting clicked the Elements attached to the DOM are changing as a result Selenium Webdriver detects this as a change in the current Active Element as a result StaleElementReference Exception thrown.
In order to get rid of the Exception, you can add wait statement in between or there is a great way to handle StaleElementReference Exception given here
Thanks :)
I wouldn't use .SendKeys() to scroll the page. It won't be consistent. Imagine if the page is longer or shorter... how many times will you need to scroll? I think a better approach is to use JS to scroll the page to the desired element.
public void ScrollToFooter()
{
footer = webDriver.FindElement(By.ClassName("c-footer"));
// MoveToElement does not work for Firefox, so a workaround is needed
if (webDriver is FirefoxDriver)
{
IJavaScriptExecutor jse = (IJavaScriptExecutor)webDriver;
jse.ExecuteScript("arguments[0].scrollIntoView();", footer);
}
else
{
actions.MoveToElement(footer).Perform();
}
}
If you decide to stick with your method, you have a bug because of a missing else. If the driver is FF, after your scrolldown code is executed, it will execute .MoveToElement() and fail.
You could simplify this function to just use JS for all drivers.
public void ScrollToFooter()
{
footer = webDriver.FindElement(By.ClassName("c-footer"));
IJavaScriptExecutor jse = (IJavaScriptExecutor)webDriver;
jse.ExecuteScript("arguments[0].scrollIntoView();", footer);
}
Instead of
actions.SendKeys(Keys.ArrowDown).Perform();
I suggest:
webDriver.FindElement(By.cssSelector("body")).sendKeys(Keys.ArrowDown);

Program doesn't wait for modal dialog

With this program I am attempting to have the user select a text file that is a representation of a 4x4 sudoku problem. My agent will then take this file and attempt to solve the sudoku puzzle.
The problem I'm running into is that I can't seem to figure out how to get the proper file selected, and then passed into the method call for processing.
This is the file selector class I've created. So far it successfully brings up a button, and when clicked brings up the computer's file structure so the user can select a file.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* Created by neil on 7/12/17.
*/
public class file_selector {
public JPanel panel1;
public File file;
JButton button1;
public file_selector() {
final JFileChooser fc = new JFileChooser();
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
System.out.println("You chose to open " + file.getName());
}
}
});
}
public File getFile() {
return file;
}
}
This is my main method in which I attempt to use the file that the user selected. When I put the function calls in a while loop (like it is currently) it never proceeds because the file is never set. If I don't put the function calls in a while loop, I get a nullPointerException error when I try to process the file because the file has a null value.
public class sudoku {
//create 2d array that represents the 16x16 world
public cell[][] world_array = new cell[15][15];
static File myFile;
ArrayList<String> world_constraints;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("file_selector");
file_selector fs = new file_selector();
frame.setContentPane(fs.panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
myFile = fs.getFile();
while(myFile != null) {
sudoku my_puzzle = new sudoku();
my_puzzle.solve_puzzle();
}
}
I've done a ton of searching and can't seem to find what's wrong with my file_selector class such that it isn't setting the user selected value for the file.
You call getFile immediately after showing the frame and before the user has opportunity to click anything. Since the condition for while is false, the loop ends immediately and the method doesn't do anything afterwards, in particular it never calls getFile again.
Two options:
Make the button solve the puzzle, not just set file (easier, just change actionPerformed method).
Make file_selector emit an event when a file is selected and add a listener to it (this can be a challenge for you).

Getting Tab parameters inside LaunchConfigurationDelegate

I have a custom launch configuration. It currently has a JavaArgumentsTab() where I can enter things for VM arguments and Program arguments. But how do I actually get any values entered there?
Ideally I would get them inside my LaunchConfigurationDelegate's launch() method. I expected to find any text entered as arguments inside the LaunchConfiguration or other parameters to that method, and I'm sure this is a newbie question, but I really haven't found anything promising.
TabGroup:
public class LaunchConfigurationTabGroup extends AbstractLaunchConfigurationTabGroup {
#Override
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
new JavaArgumentsTab(),
new CommonTab()
};
setTabs(tabs);
} }
LaunchConfigurationDelegate:
public class LaunchConfigurationDelegate implements ILaunchConfigurationDelegate {
#Override
public void launch(ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
// How to get anything entered on my Java tab here...?
} }
Everything from the tabs should already have been set as attribute values in the ILaunchConfiguration when launch is called.
The settings from JavaArgumentsTab are stored in the attributes using constants from IJavaLaunchConfigurationConstants.

Flow of initializing objects in XAML?

I'm not sure but from my hours of debugging, this should be the best description of my problem I can give.
I'm creating a WinRT app, there are two pages- Main Page and Details Page. Inside Main Page constructor, I have initialized a listbox. On click of any of the element of listbox, user is taken to the Details page.
I'm just learning all this and design may not be best but here is what I did.
I took a static variable in MainPage.cs, and set it to point to the element which is clicked by the user. Now in the constructor of the Details page, I used this static variable to set the datacontext of Details Page itself.
What flow I'm expecting is:-
MainPage is created first. Listbox is setup.
User will click on any of the element of listbox. Itemclick event handler runs. It will set the static variable (of Mainpage.cs) to hold the infomation which item is clicked and navigate user to the Details page.
In Details page constructor, I have set the datacontext to point to some information based on the value of static variable mentioned in the previous step.
It works for most of the times, but once in like every 5 times, The Details page constructor throws an exception stating the static variable is not initialized yet. Why is Details page's constructor running when I'm starting the app? and why only sometimes? Do I need to set DataContext of Details Page in some other method instead of constructor?
The code is somewhat complex and too much in terms of domain of the problem so I'm avoiding posting it. But if I'm failing to explain the problem please tell, I'll post it keeping it as related as I can.
CODE:-
This is the method called when an item in listbox is clicked--will take user to the Details page.
private void overviewlistbox_Tapped_1(object sender, TappedRoutedEventArgs e)
{
MatchOverview selectedmatch = (sender as ListBox).SelectedItem as MatchOverview;
matchFullDetails = new ObservableCollection<Match>();
foreach (Match m in UpdateController.matchList)
{
if (m.matchDescription == selectedmatch.matchDesc)
{
matchFullDetails.Add(m);
break;
}
}
if(!(matchFullDetails.Count == 0))
this.Frame.Navigate(typeof(Details));
}
This is the constructor for Main Page:-
public static ObservableCollection<Match> matchFullDetails;
public MainPage()
{
matchFullDetails = new ObservableCollection<Match>();
this.InitializeComponent();
UpdateController update = new UpdateController(); // Creating new object will update the overview_list of UpdateController(static list).
overviewlistbox.ItemsSource = UpdateController.overview_list;
}
And this is the code for constructor of details page, where the exception occurs:-
public static ObservableCollection<Match> matchdetails = new ObservableCollection<Match>();
DispatcherTimer dtm_detailspage = null;
public Details()
{
this.InitializeComponent();
matchdetails = MainPage.matchFullDetails; // matchdetails.Last<>() is take because we only need item which is added latest to the collection.
if (matchdetails.Last<Match>().type == "TEST") // Exception is thrown here--Initialization
// error. When I check MainPage.matchFullDetails,
// no data is shown which means its not yet
// initialized. Also the exception is thrown either at
// the start of the app, or when details page is visited. That too once in 4-5 times, not always.
{
matchdetails.Add(matchdetails.First<Match>() as TestMatch);
}
if (matchdetails.Last<Match>().type == "ODI")
{
matchdetails.Add(matchdetails.Last<Match>() as ODIMatch);
}
if (matchdetails.Last<Match>().type == "T20")
{
matchdetails.Add(matchdetails.Last<Match>() as T20Match);
}
}
Exception Screenshot:-
Call Stack data on bug encounter:-
[Cricket Expert.exe!Cricket_Expert.Details.Details() Line 33 + 0x5 bytes
[External Code]
Cricket Expert.exe!Cricket_Expert.Common.SuspensionManager.RestoreFrameNavigationState(Windows.UI.Xaml.Controls.Frame frame) Line 236 + 0x5 bytes
Cricket Expert.exe!Cricket_Expert.Common.SuspensionManager.RestoreAsyn() Line 124 0x8 bytes
Cricket Expert.exe!Cricket_Expert.App.OnLaunched(Windows.ApplicationModel.Activation.LaunchActivatedEventArgs args) Line 74 + 0x5 bytes
[External Code]
MAJOR UPDATE:
I finally found the flaw. If the Details page is still active, and the app is restarted, the problem occurs.
Is there a solution to this problem??
You can pass information on what needs to be displayed on the Details page through the Navigate call and set the DataContext in OnNavigatedTo override to avoid using static variables. Pages don't get created unless you do it specifically e.g. by navigating to one. They might not be recreated if a page has NavigationCacheMode changed from the default (Disabled) so instances of the page can be reused during navigation calls. Ultimately it's hard to say what's wrong but it seems like something in your code and we couldn't help you if you don't share a sample that reproduces the problem.
*EDIT
One way to debug Details being created before MainPage would be to add this code at the beginning of the Details constructor:
if (MainPage.matchFullDetails == null)
{
System.Diagnostics.Debugger.Break();
}
Then look at the Call Stack panel in Visual Studio to see how it gets constructed.
One way to see if matchFullDetails is ever set to null is to search for its assignment (put a cursor on matchFullDetails in Visual Studio code editor and hit Shift+F12).
Another way would be to make matchFullDetails into a property and test it like this:
private static ObservableCollection<Match> _matchFullDetails;
public static ObservableCollection<Match> matchFullDetails
{
get
{
return _matchFullDetails;
}
set
{
if (value == null)
{
System.Diagnostics.Debugger.Break();
}
_matchFullDetails = value;
}
}
*EDIT 2
You can initialize your static property in a static constructor like this:
public static ObservableCollection<Match> matchFullDetails;
static MainPage()
{
matchFullDetails = new ObservableCollection<Match>();
}
public MainPage()
{
this.InitializeComponent();
UpdateController update = new UpdateController(); // Creating new object will update the overview_list of UpdateController(static list).
overviewlistbox.ItemsSource = UpdateController.overview_list;
}
this will prevent the null reference exception but won't fix your problem overall. When your app gets suspended and resumed - you have to restore the full state and it seems like your matchFullDetails collection would need to be serialized and saved to disk when your app gets suspended. Alternatively you might simply ignore the suspension manager call in App.xaml.cs and always start on home page, though that's not a very good experience and I am not sure if it satisfies app certification.