Scanner Mismatch Exception when reading text file - java.util.scanner

My scanner is reading from a text file with the use of a delimiter. However when I run the program the only line that gets printed out is the first line of data then I get thrown an input mismatch exception. I believe the error is that it doesn't move onto the next line. I understand how the mismatch works I am just unsure how to fix it. I have tried putting scanner.nextLine(); in as you can see in my code below.
Here is my code for the scanner :
/**
* Method for reading the data from the electricToolData.txt file.
*/
public void readElectricToolData()
{
Frame myFrame = null; // initialises frame to null
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
String directoryPath = fileBox.getDirectory();
String filename = fileBox.getFile();
System.out.println(filename + " " + directoryPath); // prints out name of file and directory path
try {
File dataFile = new File(filename);
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
//if statement checks if line starts with either "//" or space.
if (lineOfText.startsWith("//") || lineOfText.isEmpty())
{
}
else // now got real data
{
Scanner scanner2 = new Scanner(lineOfText);
scanner2.useDelimiter(",");
lineOfText.trim();
System.out.println(lineOfText);
while(scanner2.hasNext())
{
//lineOfText.trim();
boolean mRechargeable = scanner.nextBoolean();
String mPower = scanner.next();
String mToolName = scanner.next();
String mItemCode = scanner.next();
int mTimesBorrowed = scanner.nextInt();
boolean mOnLoan = scanner.nextBoolean();
int mCost = scanner.nextInt();
int mWeight = scanner.nextInt();
scanner.nextLine();
ElectricTool electricTool = new ElectricTool(mToolName, mItemCode, mTimesBorrowed, mCost, mWeight, mPower);
toolsList.add(electricTool);
}
}
//System.out.println(lineOfText); // prints out string
}
scanner.close();
scanner.close(); // closes scanner
}
catch(FileNotFoundException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
The error gets shown at the boolean mRechargeable = scanner.nextBoolean();.
Here is the data file :
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
// data is rechargeable, power, toolName, itemCode, timesBorrowed, onLoan, cost, weight
true,18V,Makita BHP452RFWX,RD2001,12,false,14995,1800
true,10.8V,Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
false,1350W,DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
false,1500W,Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
true,10.8V,Bosch GSR10.8-Li Drill Driver,RD3021,25,true,9995,820
false,900W,Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
true,10.8V,Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
true,18V,DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
false,2100W,Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400

The problem is that String.trim() doesn't work the way you think it does: it doesn't mutate the String it is called on, but returns a new String that effectively has the whitespace removed. This is causing the line to not be trimmed, and that "blank line" that has a lot of space characters on it then fails to be parsed with your first scanner.nextBoolean() call.
So, update:
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
to be:
// read the next line of the file, removing enclosing whitespace
String lineOfText = scanner.nextLine().trim();
Comments should ideally preceed the line, as it is easier to read and format, and more obvious that it is a comment. Also remove the redundant lineofText.trim(); later in the code.
Further, remember to close all Scanner instances when finished (so here one for each line, and one for the file).
The next problem is that in the inner loop, where you construct your ElectricTool instances, you are calling methods on scanner, rather than scanner2 (rename this to something more semantic, eg itemScanner):
Scanner itemScanner = new Scanner(lineOfText);
itemScanner.useDelimiter(",");
boolean mRechargeable = itemScanner.nextBoolean();
String mPower = itemScanner.next();
String mToolName = itemScanner.next();
String mItemCode = itemScanner.next();
int mTimesBorrowed = itemScanner.nextInt();
boolean mOnLoan = itemScanner.nextBoolean();
int mCost = itemScanner.nextInt();
int mWeight = itemScanner.nextInt();

Related

How to insert/replace string value into another string value at certain place?

This is an uploading tool. I am trying to rename a file name if it is existed in the folder already.
The plan is to add a number after the file name. For example, if the file name is Hello.doc, it will be saved as Hello2.doc.
The problem is, the file name & file type are always different. It can be Goodbye.pdf/capture.png. I am not sure how to insert the number in the correct place.
if (System.IO.File.Exists(savepath))
{
int counter = 2;
while (System.IO.File.Exists(savepath))
{
string newFileName = fileName + counter;
tempFileName = newFileName.Insert/replace //Not sure what to do here
savepath += tempFileName;
counter++;
}
FileUpload.SaveAs(savepath);
lblUpload.Text = "A file with the same name already exists." + " Your file was saved as " + tempFileName;
}
Does someone know? Thanks!
Please let me know if this is what you were looking for. Used StringBuilder to avoid creating new String objects after every concatenation.
String[] filepath = filename.split(".");
// filepath[0] -> filename
// filepath[1] -> extension
StringBuilder newFilename = new StringBuilder(filepath[0]);
// add number
newFilename.append(2);
// add period
newFilename.append(".");
// add extension
newFilename.append(filepath[1]);
return newFilename.toString();

string automatically converted in spring

I'm working on a project in Spring using SpringMVC. I'm importing data from (.xls) files .
the problem is that:
I'm reading this value "945854955" as a String but saved in DB as "9.45854955E8"
this value "26929" saved as "26929.0"
this value "21/05/1987" saved as "31918.0"
/read Code
// import ...
#RequestMapping(value="/read")
public String Read(Model model,#RequestParam CommonsMultipartFile[] fileUpload)
throws IOException, EncryptedDocumentException, InvalidFormatException {
List<String> liste = new ArrayList();
Employe employe = new Employe();
String modelnom = null;
liste = extraire(modelnom); //See the second code
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
m++;
}
employe.setNomEmploye(liste.get(29*m+1));
//...
employe.setDateNaissance((String)liste.get(29*m+8).toString()); // here i had the date problem
employe.setDateEntree((String)liste.get(29*m+9).toString()); // here i had the date problem
employe.setDateSortie((String)liste.get(29*m+10).toString()); // here i had the date problem
// ...
employe.setNumCpteBanc(liste.get(29*m+17)); // here i had the first & second case problem
employe.setNumCIMR(liste.get(29*m+19)); // here i had the first & second case problem
employe.setNumMUT(liste.get(29*m+20)); // here i had the first & second case problem
employe.setNumCNSS(liste.get(29*m+21)); // here i had the first & second case problem
boolean bool=true;
List<Employe> employes = dbE.getAll();// liste des employes
for (int n=0;n<employes.size();n++) {
if (employes.get(n).getMatriculeMY() == (int)mat ) {
bool= false;
}
}
if (bool) {
dbE.create(employe);
}
}
return "redirect";
}
extraire code
private List<String> extraire (String nomFichier) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(nomFichier));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
// recup une ligne
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* Pour verifier si une ligne est vide. (for verifing if the line is empty)
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
}
Excel's tries to data type cells and sometimes when you explicitly specify the data type Excel may try and cast the cell. You can try to right click on the cell and select 'Format Cell', then select 'Text' as the type (Category). However, at parse time it may still get hosed up.
Your quickest solution might be to save the file as a CSV and use that. You can still edit it in Excel. Although you will need to do some validation to ensure Excel isn't trying to do the above conversions on CSV save as. There are a lot of good Java CSV parsers out there OpenCSV, Super CSV.
The most time consuming, but probably the most correct way, if you want to continue to use Excel, is build a middle ware layer that parses the row and correctly identifies and formats the cell values. Apache POI and HSSF & XSSF can be used. Be warned that to handle xls and xlsx requires two different sets of libraries and often enough abstraction to handle both.
See https://poi.apache.org/spreadsheet/
As an Example:
protected String getCellValue(final Cell cell){
if (null == cell) { return null; }
// For Excel binaries 97 and below, The method of setting the cell type to CELL_TYPE_STRING converts the
// Formatted to date to a short. To correct this we check that the cell type is numeric and the check that it is
// date formatted. If we don't check that it is Numeric first an IllegalAccessorException is thrown.
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC && isCellDateFormated(cell) {
// isCellDateFormated is seperate util function to look at the cell value in order to determine if the date is formatted as a double.
// is a date format.
return // do date format procedure.
}
cell.setTypeCell(Cell.CELL_TYPE_STRING);
return cell.toString();
}
Hope this helps.
============Update==================
Instead of calling methods like "getNumericCellValue()" try setting the cell type to String and using toString like the example above. Here is my test code.
Note the xls file has one row and 4 cells in csv: "abba,1,211,q123,11.22"
public void testExtract() throws Exception{
InputStream is = new FileInputStream("/path/to/project/Test/src/test/java/excelTest.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIter = sheet.iterator();
while (rowIter.hasNext()){
HSSFRow row = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
while (cellIter.hasNext()){
Cell cell = cellIter.next();
System.out.println("Raw to string: " + cell.toString());
// Check for data format here. If you set a date cell to string and to string the response the output is funky.
cell.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("Formatted to string: " + cell.toString());
}
}
is.close();
}
Output is
Raw to string: abba
Formatted to string: abba
Raw to string: 1.0
Formatted to string: 1
Raw to string: 211.0
Formatted to string: 211
Raw to string: q1123
Formatted to string: q1123
Raw to string: 11.22
Formatted to string: 11.22

Comparing excel value with console output using selenium web driver

I am storing excel values in 1st array and console output values in 2nd array. Then I am comparing excel value with console output one by one .I have debug code and it stores value proper in arrays. But it always print "FALSE" even if value matches true.
My latest code is given below :
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=1YaGVMutHcXN8gf39ID4Aw&gws_rd=ssl#q=what+is+software+testing");
java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
int sizecount = links.size();
System.out.println(sizecount);
//READING DATA FROM EXCEL FROM 1ST COLUMN
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
String exceldata[] = new String[20];
for (int i=0;i<=sh.getLastRowNum();i++)
{
HSSFRow row = sh.getRow(i);
exceldata[i]= row.getCell(count).toString();
System.out.println(exceldata[i]);
}
String linkdata[] = new String[20];
for(int j=1;j<=links.size()-1;j++)
{
linkdata[j] = links.get(j).getText();
System.out.println(linkdata[j]);
}
for(int k=0;k<links.size()-1;k++)
{
if(exceldata==linkdata)
{
System.out.println("TRUE");
}
else
{
System.out.println("FALSE");
}
}
driver.close();
}
}
Note : I have tried with operator == and .equals both.
I've told you few issues in your program, you can modify your program according to that.
Issue 1
When you are storing the value in exceldata and linkdata array, you are taking different index, exceldata array is storing value from index 0 and linkdata is storing value from index 1, so you need to modify your program something like below:
for(int k=0;k<links.size()-1;k++){
if(exceldata[k].trim().equals(linkdata[k+1].trim())){
System.out.println("TRUE");
}else{
System.out.println("FALSE");
}
}
There was one more issue, I've already told you.
You are good to go now.

Delete Selected Text from Textbox and Enter New Char in C#.NET

I am trying to delete selected text from textbox and enter new character in place of it.
For example, if textbox consists of 123456 and I select 345, and press r on the keyboard, it should replace the selected text.
here is my code:
string _selectText = txtCal.SelectedText;
string _text = Convert.ToString(btn.Text);
if (_selectText.Length > 0) {
int SelectionLenght = txtCal.SelectionLength;
string SelectText = txtCal.Text.Substring(txtCal.SelectionStart, SelectionLenght);
txtCal.Text = ReplaceMethod(SelectText, _text);
}
//replace method function
public string ReplaceMethod(string replaceString, string replaceText) {
string newText = txtCal.Text.Replace(replaceString, replaceText);
return newText;
}
Can anyone show me where my mistake is?
The replace-based answer offered above may well replace the wrong instance of the selection, as noted in the comments. The following works off positions instead, and doesn't suffer that problem:
textbox1.Text = textbox1.Text.Substring(0, textbox1.SelectionStart) + textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength, textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length));
The following does what you want and then selects the replacing text :)
string _text = Convert.ToString(btn.Text);
int iSelectionStart = txtCal.SelectionStart;
string sBefore = txtCal.Text.Substring(0, iSelectionStart);
string sAfter = txtCal.Text.Substring(iSelectionStart + txtCal.SelectionLength);
txtCal.Text = sBefore + _text + sAfter;
txtCal.SelectionStart = iSelectionStart;
txtCal.SelectionLength = _text.Length;
Try this instead
if (textbox1.SelectedText.Length > 0)
{
textbox1.Text = textbox1.Text.Replace(text1.Text.Substring(textbox1.SelectionStart, textbox1.SelectionLength), btn.Text);
}
This is essentially the same as other answers, but formatted differently using C# 6.0.
// If there is selected text, it will be removed before inserting new text.
// If there is no selected text, the new text is inserted at the caret index.
string before = textBox.Text.Substring(0, textBox.SelectionStart);
string after = textBox.Text.Substring(textBox.SelectionStart + textBox.SelectedText.Length);
textBox.Text = $"{before}{insertText}{after}";
textBox.CaretIndex = $"{before}{insertText}".Length;
Note that I set the CaretIndex to a new position after changing the text. This may be useful since the caret index resets to zero when changing the text like this. You may also want to focus the textbox to draw the user's attention to the change and allow them to know where the caret currently is.

AS3 Using a variable with Transform

I have a text field and a background and want to apply color using
myColorPicker. Either the text field or background can be selected using
radioGroup1. When either radio button is selected the trace statement
traces the variable obj2Clr exactly. However when I use that variable
with Transform, I can't apply color. If I hard code and use the actual
object then it works.
Can I not use a variable with Transform or is something else missing?
My code is below:
var radioGroup1:RadioButtonGroup = new RadioButtonGroup("selObj");
bkg_rb.label = "Background";
text_rb.label = "Text";
bkg_rb.group = radioGroup1;
text_rb.group = radioGroup1;
var obj2Clr;//which object to apply color to
radioGroup1.addEventListener(MouseEvent.CLICK, getObj);
function getObj(e:MouseEvent):void {
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
} else if (text_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.info_txt";
trace(obj2Clr);
}
}
var colorTrans:ColorTransform = new ColorTransform();
var trans:Transform = new Transform(obj2Clr);
//var trans:Transform = new Transform(MovieClip(parent).design_mc.info_txt);
myColorPicker.addEventListener(ColorPickerEvent.CHANGE, changeColor);
function changeColor(event:ColorPickerEvent):void {
var myColor = "0x" + event.target.hexValue;
colorTrans.color = myColor;
trans.colorTransform = colorTrans;
trace("color selected is " + myColor);
}
Thanks for your help in advance:)
Debbie D
According to this code, obj2Clr is being initialized with a string literal?
For example, shouldn't this snippet:
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
}
be:
if (bkg_rb.selected == true) {
obj2Clr = MovieClip(parent).design_mc.bkg_mc;
trace(obj2Clr);
}
?
Thanks, yes I thought I had to use a string literal with Transform because tracing out the variable without quotes that make it a literal resulted in [object MovieClip] and [object TextField].
So I removed the quotes and Transform still is not receiving the new Transform object. Yet when I hard code (which was commented out in the above example) everything is fine. Any other area I should check?
Debbie D :)

Resources