I need to identify characters in a string using a users input - charat

For example if the user enters the string "hello world" they will then be prompted for a number. If the user enters "6" I want "w" to print
This is my work so far which doesn't seem to work
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string:");
String str = in.next();
System.out.print("Enter the index: ");
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
System.out.print(c);
}
}

This is the code. You have to use nextLine rather than next
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string:");
String str = in.nextLine();
System.out.print("Enter the index: ");
Scanner reader = new Scanner(System.in);
Integer index = Integer.parseInt(reader.nextLine());
char c = str.charAt(index);
System.out.print(c);
}}

Related

I don't know how to get the right output

import java.util.Scanner;
public class NumberWord {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String word = x.nextLine();
int number = x.nextInt();
System.out.println(number + ","+" " + word);
}
}
I want to write the program that reads in from the console a string and an integer and then outputs the integer followed a comma, a space, and then the string. For example, if the input is Wow and 10 then your output should be 10, Wow.
OK.. so this is my code, copied from yours..
public class NumberWord {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String word = x.nextLine();
int number = x.nextInt();
System.out.println(number + "," + " " + word);
}
}
And them here is the output. Isnt this as expected?
IMP: Because you are using nextLine, make sure that you are pressing Enter after intering Wow and then after 10 as well.
BTW, Are you entering 10 first and then wow like below?

Getting OutOfBoundException during a recursion code

Getting the below error while executing the code:
Exception in thread "main" h
java.lang.ArrayIndexOutOfBoundsException: 12
at com.java.program.ReverseString.main(ReverseString.java:17)
package com.java.program;
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s= new Scanner(System.in);
System.out.println("Enter Any String for recurssion");
String n = s.next();
System.out.println("The Entered Value is: " + n);
char str[]= n.toCharArray();
for (int i= str.length-1;i >= 0; i++) {
System.out.println(str[i]);
}
}
}

Extent report logs for Test Steps is not working

I have a TestNG test that has multiple methods. The extent report works in the main class but when I try to write logs for the other methods I am getting null pointer exception. All the tutorials point to writing logs in the main method but not to the other methods. I have been struggling to find a solution for this for a week now. Can somebody help me please ? Thanks
My code is some thing like this
#Test
public void TestOne()
{
extentTest = extent.startTest("TestOne");
Login.LoginToClient();
Access.AccessMainPage();
-
-
}
Public void LoginToClient()
{
***How can write an extent report log here for example - "Enter Username"
driver.findElement(By.id("username")).SendKeys(username)
-
-
}
The following is written in the main test
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod
public void tearDown(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE){
//to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName());
//to add error/exception in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable());
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
//to add screenshot in extent report
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SKIP){
extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS){
extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());
}
extent.endTest(extentTest);
}
My Full code is here
package yellowfin.bi.test;
import java.awt.AWTException;
import java.io.IOException;
import java.lang.reflect.Method;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import y.bi.create.reports.charts.ContentMenuButton;
import y.bi.create.reports.charts.ReportChartBuilder;
import y.bi.create.reports.charts.ReportFormattingPage;
import y.bi.create.reports.charts.ViewForReport;
import y.bi.login.loginPage;
import y.bi.logout.Logout;
import y.bi.screenshots.Screenshots;
import y.bi.utils.Printscreen;
import y.bi.utils.BrowserFactory;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportFormatting {
private EventFiringWebDriver driver;
private loginPage login;
private Logout logout;
private ContentMenuButton createContentMenuButton;
private ViewForReport reportView;
private ReportChartBuilder createChart;
Printscreen ps;
private ReportFormattingPage reportFormattingPage;
public ExtentReports extent;
public ExtentTest logger;
#BeforeSuite(enabled = true)
public void setUpTheTest() {
driver = (EventFiringWebDriver) BrowserFactory.selectBrowser("chrome");
}
#Parameters({ "yellowfinURL" })
#BeforeTest(enabled = true)
public void instantiatePages(String url) {
driver.get(url);
login = new loginPage(driver);
logout = new Logout(driver);
createContentMenuButton = new ContentMenuButton(driver);
reportView = new ViewForReport(driver);
createChart = new ReportChartBuilder(driver);
ps = new Printscreen(driver);
reportFormattingPage = new ReportFormattingPage(driver);
}
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod(alwaysRun=true)
public void TearDown_AM(ITestResult result) throws IOException
{
System.out.println("#After Method");
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
String image= logger.addScreenCapture(screenshotPath);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
extent.endTest(logger);
extent.flush();
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.fillInStackTrace());
}
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "fontType" ,"fontSize"})
#Test(testName = "validateDataSection", enabled = true, groups = {"Report Formatting : Data"}, alwaysRun = true, priority=1)
public void ValidateDataSection(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String ftype, String fsize) {
logger = extent.startTest("ValidateDataSection");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Checks the style "Font Type, Font Size, Bold Italic"
reportFormattingPage.DataSection(ftype,fsize);
// Access Row Highlight
reportFormattingPage.RowHighlight();
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "headerFontType", "headerFontSize", "borderWidth"})
#Test(testName = "Validate Column & Row Headings and Border", enabled = false, groups = {"Report Formatting : Column & Row Headings and Border"}, alwaysRun = true, priority=1)
public void ValidateColumnandRowHeadingsandBorder(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String headerFontType, String headerFontSize, String borderWidth) {
logger = extent.startTest("ValidateColumnandRowHeadingsandBorder");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
// validates the column and Row headings
reportFormattingPage.ColumnAndRowHandling(headerFontType, headerFontSize);
// Validates the border
reportFormattingPage.Border(borderWidth);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate Title and Description", enabled = false, groups = {"Report Formatting : Title and Description"}, alwaysRun = true, priority=1)
public void ValidateTitleandDescription(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateTitleandDescription");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Title and Description
reportFormattingPage.TitleAndDescription(displayTitleFontType,displayTitleFontSize,displayDescFontType,displayDescFontSize);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate header / Footer and Table sort", enabled = false, groups = {"Report Formatting : header / Footer and Table sort"}, alwaysRun = true, priority=1)
public void ValidateHeaderFooterandTableSort(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateHeaderFooterandTableSort");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Header and Footer page
reportFormattingPage.HeaderAndFooter();
//Validates Table sort
reportFormattingPage.TableSort();
logout.performLogout();
}
#AfterTest
public void endReport(){
extent.flush();
extent.close();
driver.quit();
}
}
import java.awt.Robot;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.asserts.SoftAssert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import yellowfin.bi.screenshots.Screenshots;
public class ReportFormattingPage {
static WebDriver driver;
static long d = 2000;
String xpathElements="//div[#class='toggleSwitchSliderInner']";
String workingDir = System.getProperty("user.dir");
ReportFormat rf = new ReportFormat();
SoftAssert sa= new SoftAssert();
Screenshots screenshot = new Screenshots();
public ExtentReports extent;
public ExtentTest logger;
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#SuppressWarnings("static-access")
public ReportFormattingPage(WebDriver driver) {
this.driver = driver;
}
public void DataSection(String FontType, String FontSize)
{
try {
logger = extent.startTest("ValidateDataSection");
//Click on Report Format
logger.log(LogStatus.INFO, "Access Report Format Button");
rf.accessReportFormat(driver);
//Click on the Toggle switch
driver.findElement(By.cssSelector("div.toggleSwitchSliderInner")).click();
Thread.sleep(d);
//Select the font type
new Select(driver.findElement(By.cssSelector("div.fontDropDown > div.styledSelect.customSelect > select"))).selectByVisibleText(FontType);
Thread.sleep(d);
//Select the font size
driver.findElement(By.cssSelector("input.broadcastInput")).clear();
driver.findElement(By.cssSelector("input.broadcastInput")).sendKeys(FontSize);
//Click on Bold
driver.findElement(By.cssSelector("div.fontStyleOptions > div > img")).click();
Thread.sleep(d);
//Select italic and underline
driver.findElement(By.xpath("//img[#src='images/format_italic.png']")).click();
driver.findElement(By.xpath("//img[#src='images/format_underline.png']")).click();
//Changing the color of the text
driver.findElement(By.xpath("//div[#class='sp-preview-inner']")).click();
rf.dragAndDrop(driver);
driver.findElement(By.xpath("(//span[#id='chooseColourText'])")).click();
//Row shading Default
driver.findElement(By.xpath("//td[contains(text(), 'Default')]")).click();
// Row Shading Alternative ------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'Alternating')]")).click();
//click on the Alternate Row Color
driver.findElement(By.xpath("(//div[contains(text(), 'Define a color to be applied to every second row in the table.')]//following::div[#class='backboneColourPicker'])[1]")).click();
//Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(143, 80, 157);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingAlternative");
//Click on Report Format
rf.accessReportFormat(driver);
//RowShading none ------------------------------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'None')]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
screenshot.captureScreenShot(driver, "RowShadingNone");
//Click on Report Format
rf.accessReportFormat(driver);
rf.clickCloseAndAccessDesignPage(driver);
//Assertions
rf.DataSectionAssertions(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingDefault");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void RowHighlight()
{
try {
//Click on Report Format
rf.accessReportFormat(driver);
// Click on the toggle switch for the Row Highlight field
driver.findElement(By.cssSelector("div.controlContainer > div.toggleSwitchSlider > div.toggleSwitchSliderInner")).click();
// Click on Row Highlight color
driver.findElement(By.cssSelector("div.sp-preview-inner.no-colour")).click();
// Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(124, 187, 0);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Robot robot = new Robot();
robot.mouseMove(200,600);
robot.delay(1500);
robot.mouseMove(200,900);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowHighlight");
}
catch (Exception e) {
e.printStackTrace();
}
}
Please check these links for the answer:
How to print logs by using ExtentReports listener in java?
https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/EmailableReporter2.java
If you have a Reporting Class say which Listens to the TestNG Listner and have ExtentReport code implemented in it you can get the TestCase Steps using Reporter Object
please see below.
Note that Reporter .log of TestNG does not have any definition for Type of Log like INFO, FATAL etc.. It just adds the Log Message.
Test case:
public class TC_1 extends BaseClass{
#Test (priority=0)
public void addNotes() throws Exception
{
if (super.search("VALUE"))
{
logger.info("Search is Successful");
Reporter.log("Search is Successful");
Assert.assertTrue(true);
}
}
Reporting:
public class Reporting extends TestListenerAdapter
{
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest logger;
public void onStart(ITestContext testContext)
{
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());//time stamp
String repName="Test-Report-"+timeStamp+".html";
htmlReporter=new ExtentHtmlReporter(System.getProperty("user.dir")+ "/test-output/"+repName);//specify location of the report
htmlReporter.loadXMLConfig(System.getProperty("user.dir")+ "/extent-config.xml");
extent=new ExtentReports();
extent.attachReporter(htmlReporter);
htmlReporter.config().setDocumentTitle("Test Project");
htmlReporter.config().setReportName("Functional Test Automation Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
public void onTestSuccess(ITestResult tr)
{
logger=extent.createTest(tr.getName());
logger.log(Status.PASS,MarkupHelper.createLabel(tr.getName(),ExtentColor.GREEN));
List<String> reporterMessages = Reporter.getOutput(tr);
for (int i = 0; i < reporterMessages.size(); i++)
{
System.out.println(reporterMessages.get(i));
logger.info(reporterMessages.get(i));
}
}
}
Firstly, I recommend to use Version 3 instead of Version 2,
As I can see in your Code, You have define Test definition but there is no such logs for that method in which you wants to generate,
Please Refer as Following, to generate logs:
You can use same way in any method,
extentTest.log(LogStatus.INFO, "Test Case Details");
Here object of ExtentTest need to declare as Class variable, So you can access it anywhere within class.
If you wants to create different Test section for Login.LoginToClient(); method, you can define it like:
Public void LoginToClient()
{
extentTest = extent.startTest("Login Test");
driver.findElement(By.id("username")).SendKeys(username);
extentTest.log(LogStatus.INFO, "User Name: " +username);
}
Hope it will works as you want to generate.

Decrypting with the wrong password, final block not properly padded

I have the following code to define a cipher class
import java.util.*;
import javax.crypto.Cipher;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.AlgorithmParameters;
import javax.crypto.*;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Cipher{
private SecureRandom rand;
private SecretKeyFactory kFact;
private Cipher AESCipher;
private SecretKey key;
public Cipher(char[] mpw, byte[] salt){
try{
kFact = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
rand = SecureRandom.getInstance("SHA1PRNG");
AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
PBEKeySpec spec = new PBEKeySpec(mpw, salt, 1024, 256);
key = new SecretKeySpec(kFact.generateSecret(spec).getEncoded(),"AES");
}catch(Exception e){
System.out.println("no such algorithm");
}
}
/*Henc[k,m] will return c such that Hdec[k,HEnc[k,m]] = m
*/
public ArrayList<byte[]> HEnc(byte[] message) throws Exception{
ArrayList<byte[]> res = new ArrayList<byte[]>(2);
AESCipher.init(Cipher.ENCRYPT_MODE ,key);
AlgorithmParameters params = AESCipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ctxt = AESCipher.doFinal(message);
res.add(0,iv);
res.add(1,ctxt);
return res;
}
public byte[] HDec(byte[] iv, byte[] cipher) throws Exception{
AESCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv) );
System.out.println("decrypting");
return AESCipher.doFinal(cipher);
}
/*public abstract byte[] HDec(SecretKey k, byte[] cipher);
*/
I am interested in decrypting cipher-text with incorrect passwords, to do so i defined the following test class,
import java.util.*;
import java.io.*;
public class testCipher{
public static void main(String[] args) throws Exception{
while(true){
Scanner sc = new Scanner(System.in);
System.out.println("Enter master password");
String pass = sc.nextLine();
System.out.println("Enter incorrect password");
String fakepass = sc.nextLine();
System.out.println("Enter message to encrypt");
String message = sc.next();
String salt = "123";
HCipher goodEnc = new HCipher(pass.toCharArray(),salt.getBytes());
HCipher badEnc = new HCipher(fakepass.toCharArray(),salt.getBytes());
byte[] toEncrypt = message.getBytes();
ArrayList<byte[]> cipher = goodEnc.HEnc(toEncrypt);
byte[] ciphertxt = cipher.get(1);
byte[] iv = cipher.get(0);
while(true){
System.out.println("Enter 1 to decrypt with correct pass, 2 to decrypt with incorrect pass and 0 to end simulation");
int i = sc.nextInt();
if(i == 1){
System.out.println("Decrypting with correct password");
byte[] plaintxt = goodEnc.HDec(iv, ciphertxt);
System.out.println(new String(plaintxt));
}
if(i == 2){
System.out.println("Decrypting with incorrect password");
byte[] plaintxt = badEnc.HDec(iv, ciphertxt);
System.out.println(new String(plaintxt));
}
if(i == 0){
break;
}
}
}
}
}
Encrypting and Decrypting using the correct password works well. However, when I try to decrypt using an incorrect password, I get the follwing error:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:420)
at javax.crypto.Cipher.doFinal(Cipher.java:1966)
at HCipher.HDec(HCipher.java:54)
at testCipher.main(testCipher.java:52)
I am guessing it has something to do with my IV but im not sure how to fix it. Does anyone have any suggestions?
AES is a block cipher that encrypts in blocks of 16 bytes. Padding is used to fill up your last block before encryption so it fits in an even number of blocks.
You are specifying PKCS5Padding with this:
AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
The padding is created in such a way that it can be recognized and removed during decrypt. If you decrypt with the wrong key the Cipher won't be able to identify a valid pad and thus give you the BadPaddingException
If you instantiate your decrypt Cipher without padding (and thus take on that responsibility yourself) you can avoid this exception.

Filereader does not go to next line

import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
My problem is that once it starts the loop it just reads the first line on the file and writes it infinitely amount of times.
What I want is for it to go to the next line and so on
(The code is basically what I want but it is not finished)
public class Lab0234
{
public static void main(String [] args) throws FileNotFoundException
{
DecimalFormat two = new DecimalFormat("00.00");
Scanner keyboard = new Scanner(System.in);
Scanner inputFile = new Scanner(new FileReader("Lab02Input.txt"));
double sPrice = inputFile.nextDouble();
double sOwned = inputFile.nextDouble();
double aDiv = inputFile.nextDouble();
double mValue;
double mYield;
mValue = getValue(sPrice, sOwned);
mYield = getYield(sPrice, aDiv);
PrintWriter reportFile = new PrintWriter("Lab02Report.txt");
reportFile.println("Stock Value and Yield Report");
reportFile.println("");
reportFile.print("Stock ");
reportFile.print("Price ");
reportFile.print("Shares ");
reportFile.print("Value ");
reportFile.print("Dividend ");
reportFile.println("Yield");
while(inputFile.hasNext())
{
if (inputFile.hasNext())
{
reportFile.print(" ");
reportFile.print(sPrice+" ");
reportFile.print(sOwned+" ");
getValue(sPrice, sOwned);
reportFile.print(two.format(mValue)+" ");
reportFile.print(aDiv+" ");
getYield(sPrice, aDiv);
reportFile.println(two.format(mYield)+" ");
inputFile.close();
reportFile.close();
}
/*else
{
inputFile.close();
reportFile.close();
}*/
}
//inputFile.close();
//reportFile.close();
}
public static double getValue(double sPrice, double sOwned)
{
//DecimalFormat two = new DecimalFormat("00.00"); //Decimal format
double mValue;
mValue = (sPrice * sOwned);
//System.out.printf("Stock Value is " + mValue);
return mValue;
}
public static double getYield(double sPrice, double aDiv)
{
//DecimalFormat two = new DecimalFormat("00.00"); //Decimal format
double mYield;
mYield = (aDiv * sPrice);
//System.out.printf("\nDividend Yield is " + two.format(mYield));
return mYield;
}
}
You never call next() on your inputFile:
while(inputFile.hasNext())
{
String x = inputFile.next();
if (inputFile.hasNext())
Try do it like this
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
// do somthing
}
br.close();
} catch (Exception e) {
System.out.print("Problem!");
}

Resources