for loops and if statement error occuring - java

I can't figure out why I get the error:
java.util.NoSuchElementException null(in java.util.Scanner)
in my method:
public void processTransactions(Scanner transFile){
while (transFile.hasNext()){
for(i = 0; i < ids.length; i++){
finalInventory[i] = startingInventory[i];
if(ids[i] == transFile.next()){
finalInventory[i] += transFile.nextInt();
}
}
}
}
this is my construtor:
public SoftDrinkInventory(Scanner inventoryFile) {
initializeString(names);
initializeString(ids);
initializeInt(startingInventory);
initializeInt(finalInventory);
initializeInt(transactionCounts);
while (inventoryFile.hasNext()){
names[i] = inventoryFile.next();
ids[i] = inventoryFile.next();
startingInventory[i] = inventoryFile.nextInt();
i++;
}
}
All variables have been declared previously in the class.

I'm guessing a little, but I think your code was supposed to be this.
public void processTransactions(Scanner transFile){
while (transFile.hasNext()){
String key = transFile.next();
int value = transFile.nextInt();
for(i = 0; i < ids.length; i++){
finalInventory[i] = startingInventory[i];
if(ids[i].equals(key)){
finalInventory[i] += value;
}
}
}
}
You only want to do the next() and the nextInt() once per iteration of the while loop. Currently, you are repeating the next() in every iteration of the for loop, which really isn't what you want.
Note that this isn't the most efficient solution to your problem, but it will take away your error.
Also, you haven't specified the type of ids, but I've assumed that it's a String[].

You are calling hasNext() but using nextInt() ... One solution is to use,
while (transFile.hasNextInt()){
// As before.
}
Another is to skip anything that isn't an int, perhaps like so
while (transFile.hasNext()){
if (!transFile.hasNextInt()) {
transFile.next();
continue;
}
// As before.
}

Related

For if loop wont loop: any pointers to why that might be?

This is supposed to loop 24 times; it does not, and I'm pretty confused as to why. Please help me various Kenobis out there :
private boolean simpleMove(Board bd)
{
int b = rn.nextInt(3);
for (int i = 0; i < 24; i++) {
if (bd.isVacant(i) && rul.isLegalMove(tigerLocs[b], i)) {
bd.swap(tigerLocs[b],i);
bd.setTiger(i);
tigerLocs[b] = i;
System.out.println(i);
return true;
}
else {
System.out.println(i);
}
}
System.out.println("invalid");
return false;
As the comments point out your loop will execute a maximum of 24 times.
But the return statement inside the if statement may cause it to return 'early'.
It looks like it's some kind of board game thing.
The board appears to have 24 'squares' and it makes the first legal move and returns true.
If it fails to find a legal move, it returns false.
I can't confirm the logic overall but that rationale seems sound:
If there's a move available, take it and return true.
If no move is available, make no move and return false.
If you expected it to continue, even after finding a "valid" move, then simply store the fact that a valid move has been found. This can be done in a separate boolean variable:
private boolean simpleMove(Board bd) {
int b = rn.nextInt(3);
boolean valid = false; // until proven otherwise below
for (int i = 0; i < 24; i++) {
if (bd.isVacant(i) && rul.isLegalMove(tigerLocs[b], i)) {
bd.swap(tigerLocs[b],i);
bd.setTiger(i);
tigerLocs[b] = i;
valid = true;
}
System.out.println(i); // why output HERE when we have a return value?
}
if (!valid) {
System.out.println("invalid"); // why output HERE when we have a return value?
}
return valid;
}
It's unclear if multiple "valid" moves could be found, and whether that would be a problem when you "swap" or not. If there is only ever one possible move, then there would be no need to continue iterating with the for loop; simply return in the body like you were doing.

Find bug in implementation of algorithm that finds minimum of an array of integers

Recently, I tried to write a Java program which searches for the minimum of an array.
I tried to write it in a different way, I know there are more simple ways to do that but I want to know why my program does not work.
Here is the source code :
public int minimum(int [] t) {
int min,i,j;
i=j=t.length/2;
min=t[t.length/2];
while(j!=0 || i!=t.length-1) {
while( t[i]>=min) {
i++;
if(i==t.length) {
i=t.length-1;
continue;
}
}
while(t[j]>=min) {
j--;
if(j==-1) {
j=0;
continue;
}
}
if(t[i]<=min && t[j]<=min) {
if(t[i]<=t[j]) min=t[i];
else min=t[j];
}
}
return min;
}
Thanks.
Before you read the answer you should try debugging your code to figure this out by yourself.
I think your code loops infinitely in one of those inner while loops because the end condition
if(i==t.length) {
i=t.length-1;
continue;
}
only resets the i one step back and the continue restarts the while loop. You probably meant to have the break keyword there instead of the continue in which case your code will continue with the other inner while loop.
there is some logic errors in my code , and it get infinitely going through the two loops , i fixed the loops by changing continue with break and i modify the last condition by setting || instead of && (that was a logic mistake), and it works now .
thanks guys.
here is the new source code:
public int minimum(int [] t) {
int min,i,j;
i=j=t.length/2;
min=t[t.length/2];
while(j!=0 || i!=t.length-1) {
while( t[i]>=min) {
i++;
if(i==t.length) {
i=t.length-1;
break;
}
}
while(t[j]>=min) {
j--;
if(j==-1) {
j=0;
break;
}
}
if(t[i]<=min || t[j]<=min) {
if(t[i]<=t[j]) min=t[i];
else min=t[j];
}
}
return min;
}

java equivalent Iterator.remove in c#

The code has migrated from Java to C #.
Java code :
for (List<ItemNY> level : highU.getLevels())
{
Iterator<ItemNY> iterItemset = level.iterator();
while(iterItemset.hasNext())
{
ItemNY c = iterItemset.next();
// Code...
if(c.getU() < min)
{
iterItemset.remove();
highU.decreaseCount();
}
}
}
C# code : (Code written after convert)
foreach (List<ItemNY> level in highU.getLevels())
{
ItemNY c;
using (IEnumerator<ItemNY> iterItemset = level.GetEnumerator())
{
while (iterItemset.MoveNext())
{
c= iterItemset.Current;
//CODE
foreach (TransactionTP transaction in database.getTransactions())
{
int transactionUtility = 0;
int matchesCount = 0;
for (int i = 0; i < transaction.size(); i++)
{
if (c.getItems().Contains(transaction.get(i).item))
{
transactionUtility += transaction.getItemsUtilities()[i].utility;
matchesCount++;
}
}
if (matchesCount == c.size())
{
c.incrementUtility(transactionUtility);
}
}
//END CODE
if (c.getU() < min)
{
iterItemset.remove(); //ERROR
highU.decreaseCount();
}
}
}
}
I want to remove an item from IEnumerator, how can I do this?
Note : The code written in the C # section is more complete, More code is written in the (CODE) to (END CODE) section.
I want to remove an item from IEnumerator, how can I do this?
Easy: you don't.
I do not know Java, but that idea does not make sense in .NET. As you can read in the documentation:
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
As it is also mentioned, foreach should be used instead of IEnumerator<T> directly:
foreach (List<ItemNY> level in highU.getLevels())
{
foreach (var item in level)
{
if (item.getU() < min)
{
level.Remove(item); //Error, you are modifying a collection being enumerated
highU.decreaseCount();
}
}
}
You would have to put the elements that match the filter in a new collection so you could remove them from level.
foreach (List<ItemNY> level in highU.getLevels())
{
var filteredItems = new List<ItemNY>();
foreach (var c in level)
{
foreach (TransactionTP transaction in database.getTransactions())
{
int transactionUtility = 0;
int matchesCount = 0;
for (int i = 0; i < transaction.size(); i++)
{
if (c.getItems().Contains(transaction.get(i).item))
{
transactionUtility += transaction.getItemsUtilities()[i].utility;
matchesCount++;
}
}
if (matchesCount == c.size())
{
c.incrementUtility(transactionUtility);
}
}
if (c.getU() < min)
{
filteredItems.Add(c);
highU.decreaseCount();
}
}
foreach (var item in filteredItems)
{
level.Remove(item);
}
}
If the true goal is to remove items from the list then I would use List.RemoveAll, with conditions defining which to remove.
If you need the extra counter update then you take a size before and after. Though at least in the presented case there is no need for the decreaseCount method, as it appears to track size of the list, so I would drop the method, and rely on the list Count.

How to Make Program flow control jump back to a former loop in java?

So I have written a code that allows a user to find a word in a TextArea. I have nearly succeeded but for one thing. here, I will show you all the code and tell my problem.
if(ta.getText().length() != 0 && t1.getText().length() != 0)
{
char c1[] = ta.getText().trim().toCharArray();
char c2[] = t1.getText().trim().toCharArray();
for(int i=startFlag;i<c1.length;i++)
{
if(c1[i]==c2[0])
{
start = i;
break;
}
}
k=start;
for(int i=0;i<c2.length;i++)
{
if(c2[i] != c1[start++])
{
}
else
countFlag++;
}
if(countFlag==c2.length)
{
ta.select(k,c2.length);
startFlag++;
}
}
For reference, ta is the TextArea and t1 is the TextField where the user enters a word to find. i have a problem in the second for loop. What should I write in the if () block there so that whenever c2[i] != c1[start++] the control is shifted to the first for loop, that would again determine the value of start?
Create a method to get "start" that you can then call whenever you want.
if(ta.getText().length() != 0 && t1.getText().length() != 0)
{
char c1[] = ta.getText().trim().toCharArray();
char c2[] = t1.getText().trim().toCharArray();
k=getStart(startFlag, c1.length);
for(int i=0;i<c2.length;i++)
{
if(c2[i] != c1[start++])
{
start = getStart(startFlag, c1.length);
}
else
countFlag++;
}
if(countFlag==c2.length)
{
ta.select(k,c2.length);
startFlag++;
}
}
And getStart() is:
public int getStart(int startFlag, int length) {
for(int i=startFlag;i<length;i++)
{
if(c1[i]==c2[0])
{
return i;
}
}
}
You may need different inputs to getStart(), but hopefully this gets across the general idea.
The way your code is set up right now, what you're asking for is impossible. To do what you're asking, you'll need to refactor your current code into different methods. More specifically, you'll need to put the for loops into their own methods and then call these methods.
So what you would need to do is make a separate method for the for loop.
public static int startForLoop(int i) {
for(int i=startFlag;i<c1.length;i++)
{
if(c1[i]==c2[0])
{
start = i;
break;
}
}
}
Then you can just call startForLoop(0) initially and in the 2nd for loops if statment:
if(c2[i] != c1[start++])
{
startForLoop(start+1)
}
This will continue the for loop where it left off. If you need to run the 2nd for loop again then you have to make a separate method for it as well and basically place both of them in a while loop that continues till you find the result you want in the 2nd for loop.
May be this code piece help you what you are looking for.
Basically it moves along with the string to be searched in keeping in mind the index of the string to be searched for.
Sorry but i have implemented it in java, but the notion is same and the result returned is the best what i got.you must give it a try!
private static String searchString(String searchIN,String searchFOR){
if (searchFOR != "") {
int index = searchIN.toUpperCase().indexOf(searchFOR.toUpperCase());
String before = "";
String highlighted = "";
String after = "";
while (index >= 0) {
int len = searchFOR.length();
before = searchIN.substring(0, index);
highlighted = "\"" + searchFOR + "\"";//do what ever you want to do with searched string
after = searchIN.substring(index + len);
searchIN = before + highlighted + after;
index = searchIN.toUpperCase().indexOf(searchFOR.toUpperCase(), index + highlighted.length());
}
}
return searchIN;
}

Why can't I return an index of an array as int in Java?

Apparently Eclipse keeps giving me an error asking me to return an int. Is array[i] not considered an int or we cant return an index of a array in java like this? Anyone out there that can help me?
public static void main(String[] args){
int[] array = {10,6,4,3,12,19,18};
int z = quick_find_1d_peak1(array);
System.out.println(z);
}
public static int quick_find_1d_peak1(int[] inputArray){
for (int i=0 ; i<inputArray.length ; ){
if (i==0 && inputArray[i] >= inputArray[i+1]){
return inputArray[i];
} else if (i==inputArray.length && inputArray[i] >= inputArray[i-1]){
return inputArray[i];
} else if (inputArray[i] >= inputArray[i-1] && inputArray[i] >= inputArray[i+1]){
return inputArray[i];
} else {
i++;
}
}
}
In quick_find_1d_peak1, your last conditional (the else) doesn't return anything. This means it is possible nothing gets returned ever. To fix this, either return something in the else (which is probably not what you want to do because you're incrementing i to go to the next one), or return something after the for loop so something will get returned no matter what.
You're not guaranteed to return a result. For example, suppose inputArray is empty, then the for loop never gets entered, and nothing is returned. Or if none of the conditions inside the loop ever fire, then your else doesn't return anything.
You have to guarantee that you return something in a method (or throw an exception).
You may want to use a try-catch block or return something if none of your conditions are fullfiled(like default in a switch perhaps).
http://www.dreamincode.net/forums/topic/22661-exception-basics-try-catch-finally/
Hope this helps.
Cheers!

Categories