Reputation: 35
public static void main(String args[])
{
ArrayList <Integer> seq = new ArrayList<Integer>();
Scanner kbReader = new Scanner(System.in);
int iterations = 0;
System.out.println("Enter a number sequence(no spaces, only commas)");
String j = kbReader.nextLine();
kbReader = new Scanner(j);
kbReader.useDelimiter("\\D");
//adds input to array list
while(kbReader.hasNextInt())
{
int i = kbReader.nextInt();
seq.add(i);
}
while(seq.size() > 0)
{
//removes zeros and numbers behind
if(seq.contains(0))
{
int zeroSearch = seq.lastIndexOf(0);
for(int c = zeroSearch; c >= 0; c--)
{
seq.remove(c);
}
iterations++;
}
//number operations
int largest = Collections.max(seq);
int largeLoc = seq.lastIndexOf(largest);
if(largest % 2 == 0)
{
largest = largest -2;
iterations++;
}
else
{
largest--;
iterations++;
}
seq.set(largeLoc, largest);
}
System.out.println(iterations + "moves" required);
}
For some reason, the max method will not work in this loop and returns the error "java.util.NoSuchElementException". The directions read "Given a number sequence, remove all the zeros, if any, and all the digits to their left. Then find the largest remaining digit and if it is even subtract 2 from it or if it is odd subtract 1 from it. If two or more digits become tied as the largest digit, use the rightmost digit as the largest. Repeat the application of the rules to the sequence. How many moves were required to delete the sequence?"
Upvotes: 0
Views: 1793
Reputation: 11483
This would be a case where you go read the javadoc for java.util.Collections#max
to see why it would throw that:
Throws:
NoSuchElementException - if the collection is empty.
So clearly seq
is empty (meaning kbReader
probably had nothing to read). Add debug to your code to see this more clearly (such as the input/output).
Upvotes: 3