I have a while condition, that reads from a text file while the file has next float (scanner.hasNextFloat()) and assigns the floats to an array. however, I am getting a java.util.InputMismatchException error.
This is my code:
int index = 0;
DistanceEventList.resetCurrent();
String a = "list";
while (scanner.hasNextLine()) {
if (scanner.hasNextFloat()){
DistanceEventList.nextCurrent();
while (DistanceEventList.endList()){
Float NextScore = scanner.nextFloat();
DistanceEventList.getCurrent().distance[index] = NextScore;
DistanceEventList.nextCurrent();}
DistanceEventList.resetCurrent();
index ++;}
else if (scanner.nextLine().equals("list")){
continue;
}}
The above raises the error, I modified a few things to check where the error was and run this code:
int index = 0;
DistanceEventList.resetCurrent();
String a = "list";
while (scanner.hasNextLine()) {
if (scanner.hasNextFloat()){
System.out.println(scanner.nextFloat());}
else if (scanner.nextLine().equals("list")){
continue;}
}
Is there something i am missing here? i cant work out why one gets an input InputMismatchException on the scanner.nextFloat() while the other doesn't.
exert from text file:
65.88782541429404
53.37054214310881
61.51132170748031
60.83640164272022
67.7342725889695
list
65.82330621202783
53.57119546501669
Thanks in advance
Inside the while you meet the "list" row.
while (DistanceEventList.endList()){
Float NextScore = scanner.nextFloat();
DistanceEventList.getCurrent().distance[index] = NextScore;
DistanceEventList.nextCurrent();}
I would add while (DistanceEventList.endList() && scanner.hasNextFloat())
Related
Background
Building an Assembler in Java:
I'm trying to read user's input into an ArrayList named v.
If the user enters an instruction that matches one of the String-array table, then the corresponding opcode will be calculated and output into a textfile.
Problem
However, after inputting the nop instruction and trying to add another instruction, I got an index out of bounds exception.
Source Code
//Array of instructions
String table[] = {"LI", " MALSI", "MAHSI", "MSLSI", "MSHSI", "MALSL", "MAHSL",
"MSLSL", "MSHSL", "NOP", "A", "AH", "AHS", "AND", "BCW", "CLZ", "MAX", "MIN",
"MSGN", "MPYU", "OR", "POPCNTH", "ROT", "ROTW", "SHLHI", "SFH", "SFW", "SFHS", "XOR "};
//Array of binary values of the instructions
String table2[] = {"0", "10000", "10001", "10010", "10011", "10100", "10101",
"10110", "10111", "1100000000000000000000000", "1100000001", "1100000010", "1100000011",
"1100000100", "1100000101", "1100000110", "1100000111", "1100001000", "1100001001",
"1100001010", "1100001011", "1100001100", "1100001101", "1100001110", "1100001111",
"1100010000", "1100010001", "1100010010", "1100010011"};
// TODO code application logic here
Scanner s = new Scanner(System.in);
String ins = "";
String fileName = "outfile.txt";
System.out.println("Please enter MISP function, enter Q to Quit: ");
boolean q = true;
String op = "";
int c = 0;
String array[] = new String[64];
//Loop to keep accepting userinput
while (q) {
//accepts the user input
ins = s.nextLine();
//arraylist to hold user input
List<String> v = new ArrayList<String>();
//adds the user input to the arraylist
v.add(ins);//user input to nop opcode
if (v.get(0).toUpperCase().equals("NOP")) {
op = "1100000000000000000000000";
} else if (v.get(1).toUpperCase().equals("LI"))//li opcode
{
String p[] = v[1].split(",", 1);
op = "0";
op += toBinary(p[0], 3);
op += toBinary(p[1], 16);
op += toBinary(p[2], 5);
Error Stacktrace I got
Exception in thread "main" java.lang.IndexOutOfBoundsException:
If you guys could help it would be appreciated.
This loop will never end.
while (q)
I have a problem with Java and Android Studio; the following code was to be a backspace button:
else if(view == btnBackspace){
int expressionLength = expression.length() - 2;
String expressionNew = newExpression.subSequence(0, expressionLength); // new expression is the t
editText.setText(expressionNew); // prints out text
}
I'm trying do a backspace button, I don't know if this is the better way of make this. So, subSequence method return's me that is a char sequence then I put a .toString() :
String expressionNew = newExpression.subSequence(0, expressionLength).toString();
But it doesn't work! The app compiles but when I press my backspace button the app stops and terminal points out the following exception:
FATAL EXCEPTION: main
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-2
at java.lang.String.startEndAndLength(String.java:583)
at java.lang.String.substring(String.java:1464) [...]
Thanks!
Check the String your want to call first.
if(!newExpression.isEmpty() && newExpression.length() > expressionLength) {
String expressionNew = newExpression.subSequence(0, expressionLength).toString();
}
Check the length before applying the string operator. Try this:
int expressionLength = expression.length() - 2;
if(expressionLength>0)
{
String expressionNew = newExpression.subSequence(0, expressionLength).toString(); // new expression is the t
editText.setText(expressionNew); // prints out text
else {
editText.setText("Empty expression string");
}
It is just if you want to know
I was reseting the var expression and the correct code for this is:
else if(view == btnBackspace){
int expressionLength = expression.length() - 1;
if(!expression.isEmpty() && expression.length() > expressionLength) {
String expressionNew = expression.subSequence(0, expressionLength).toString();
editText.setText(expressionNew);
}
else {
editText.setText("Empty expression string");
}
}
I am trying to only run nextLine() at the end of every run of the loop so that it starts the loop with the new line each iteration through, but at the end of the last run, i dont want it to run the nextLine() because it skips the data i need for the rest of my program. how do i fix this?
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
Well combining it all into that for loop seemed to work, that got me all the way through the loop, and seemed to work, but now at the start of the method it got stuck in an infinite loop
while(fileIn.hasNextLine())
{
if(fileIn.hasNext("[A-Za-z]+"))
{
do {
String hasInt = fileIn.nextLine();
if (!Character.isDigit(hasInt.charAt(0)) {
break;
}
// rest of your code here
} while(true);
You could try merging the statements into a for loop:
for(
String hasInt = fileIn.nextLine();
Character.isDigit(hasInt.charAt(0));
hasInt = fileIn.nextLine()
) {
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
}
I am not sure how clean it would be but; it seems that you could use hasInt after the while loop to get the value that you do not want to skip.
Hi you will not loss the data since the data you read last is in the hasInt variable. So use it after the while loop.
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
//use the hasInt variable here to get the last read data...
I am using temboo to get all the events for a calendar. However, i am trying to create a hashtable of the events and the days. but the for loop says its a null pointer exception even though the program is actually able to access that ith element. I have even printed it and the i is less than the size of the array. Here is the snippet code: Error is in the second line of the for loop.Errr occurs when i = 23, but items.size is 41.
GetAllEvents getAllEventsChoreo = new GetAllEvents(session);
// Get an InputSet object for the choreo
GetAllEventsInputSet getAllEventsInputs = getAllEventsChoreo.newInputSet();
// Set inputs
getAllEventsInputs.set_AccessToken(accessToken);
getAllEventsInputs.set_ClientID(clientID);
getAllEventsInputs.set_ClientSecret(clientSecret);
getAllEventsInputs.set_CalendarID(callIDs[0]);
// Execute Choreo
GetAllEventsResultSet getAllEventsResults = getAllEventsChoreo.execute(getAllEventsInputs);
results = getAllEventsResults.get_Response();
System.out.println(results);
root = jp.parse(results);
rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("items").getAsJsonArray();
System.out.println("Abour to enter the for loop\nItems:\n"+items.toString());
System.out.println("****************************\nEnter the for loop");
System.out.println("iems Size: "+items.size());
System.out.println(items.get(23).toString());
for(int i = 0;i < items.size();i++)
{
System.out.println("i: "+i);
String startTime = items.get(i).getAsJsonObject().get("start").getAsJsonObject().get("dateTime").getAsString();
System.out.println("startTime: "+startTime);
String dayKey = startTime.split("T")[0];
if(dayKey.equals(beginDate)==false | dayKey.equals(endDate)==false)
{
System.out.println(startTime + " not the one interested so skipping");
continue;
}
System.out.println("passed the first if in for loop");
String endTime = items.get(i).getAsJsonObject().get("end").getAsJsonObject().get("dateTime").getAsString();
String name = items.get(i).getAsJsonObject().get("summary").getAsJsonPrimitive().getAsString();
calendarEvent eventTemp = new calendarEvent(name,startTime,endTime);
if(table.containsKey(dayKey))
table.get(dayKey).add(eventTemp);
else
{
ArrayList<calendarEvent> schedule = new ArrayList<calendarEvent>();
schedule.add(eventTemp);
table.put(dayKey,schedule);
}
}
Set<String> key = table.keySet();
Iterator<String> it = key.iterator();
while(it.hasNext())
{
String keyValue = it.next();
System.out.println("Events on "+keyValue);
ArrayList<calendarEvent> temp = table.get(keyValue);
for(int j =0;j<temp.size();j++)
{
System.out.println(temp.get(j));
}
}
After breaking down the exception line, the exception occurs when I try to get the dateTime as string, the last part creates an exception.
Just because the ith element of an array exists, it does not mean that the element is not null.
Referencing a property or method of such an element will yield a NullPointerException.
If i went beyond the bounds of the array, you would get an ArrayIndexOutOfBoundsException instead.
Check indexed array elements for null before using them.
Sorry to be brief and not reference your code or other sources. I am on my phone. The likely source of your problem is pretty clear, though.
This is My code:
Workbook workbook = new Workbook();
workbook.open(filename);
Worksheet worksheet = workbook.getWorksheets().getSheet(sheetno);
Cells cells=worksheet.getCells();
int num=cells.getMaxDataRow();
int num1=cells.getMaxDataColumn();
int OCount=1;
for (int n1=startpos+1;n1<endpos;n1++)
{ if (cells.checkCell(n1, Colno).getValue()==null )
{ Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style);
} else if(cells.checkCell(n1, Colno).getValue().toString().length()==0) { Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style); } else{ double intCounter = Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
System.out.println(cells.checkCell(n1,Colno).getValue().toString());
if(intCounter!=Count){
Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.YELLOW);
cell.setStyle(style);
}
}
Count=Count+1;
} workbook.save("C:\\output.xls",FileFormatType.EXCEL97TO2003);
I am trying to check that Sr no is in sequential order or not. it is working fine if there is no empty string " ". For empty string it throws
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String.
Thanks in Advance....
The problem is this line of code:
Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
There you try to make a Double out of an empty String. Check the documentation and you will see that the NumberFormatException is the intended behavior. So you either have to check first if the String is empty or implement proper error handling.
Here a quote from the API for the method Double.parseDouble(...):
Throws: NumberFormatException - if the string does not contain a
parsable double.
its better to handle these cases by using a utility method.
private Double getCorrectedDouble(CellValues... ){
//check and handle empty fields
//return new Double(0) if the target is empty
}