Problems with the Iterator throwing NoSuchElementException - java

I am trying to write a program that randomizes groups of people. I am experiencing problems with the Iterator.
Here is the code:
#SuppressWarnings("deprecation")
public static void results(List<String> nameslist) {
Scanner scan = new Scanner(System.in);
int groups = 0;
int count = nameslist.size();
int done=0;
do{
System.out.println("How many people do you want per group?");
groups = scan.nextInt();
} while(groups == 0);
Iterator itr = nameslist.listIterator();
int peopledone=0;
while(peopledone<count){
int groupsdone = 0;
while (groupsdone <= groups){
groupsdone++;
peopledone = 0;
System.out.println("Group "+groupsdone+":");
while (peopledone <= groups){
try{
Object obj = itr.next();
System.out.println(obj);
peopledone++;
}catch (NoSuchElementException e){
System.out.println("Error");
Thread.currentThread().stop();
}
}
}
}
A few things to note:
nameslist is a list of letters (a-f) that I put together for testing purposes. Normally, they would be names of people in a class.
I am trying to get it to just list off names until it runs out.
Thanks so much!

Your getting the NoSuchElementException because, due to the nested loops, you are doing too many iterations. Once you reach the end of the list, if you call next() on the iterator again, it throws that exception.
Unless I'm misunderstanding what you're trying to do, this should work (there's probably a more elegant way but it at least corrects your issue):
public static void results(List<String> namesList)
{
Scanner scan = new Scanner(System.in);
int namesPerGroup = 0;
while (namesPerGroup == 0)
namesPerGroup = scan.nextInt();
int group = 0;
int namesInGroup = 0;
System.out.println("Group " + group + ": ");
for (String name : namesList)
{
if (namesInGroup == namesPerGroup)
{
group++;
namesInGroup = 0;
System.out.println("Group " + group + ": ");
}
System.out.println(name);
namesInGroup++;
}
}

You are iterating more times than there are list elements - be sure how many times your loop is going to loop.
What you are trying to do could and should be done in two lines:
Collections.shuffle(nameslist);
List<String> result = nameslist.subList(0, Math.min(count, nameslist.size()));

Related

How can I make this application properly convert these numbers and sum them?

I'm creating an application for my professor that takes several numbers entered from the user and sums them. I can't seem to figure out what I'm doing wrong. Any help will be appreciated. I tried different solutions, but I only got this far.
import java.util.*;
public class DebugSeven2
{
public static void main(String[] args)
{
String str;
int x;
int length;
int start;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner in = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = in.nextLine();
length = str.length();
for(x = 0; x <= length; ++x)
{
if(str.charAt(x) == ' ')
{
partStr = str.substring(lastSpace);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
lastSpace = x;
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
System.out.println(" -------------------" + "\nThe sum of the integers is " + sum);
}
}
First of all, this is homework and SO isn't a place where people do other's homework. That said, I'll help you with the high level overview of the solution and more didactic rather efficient solution.
Instead of spaggetti code, create several functions that do the several steps that you need to solve. This will produce a 'longer' code but it'll be easier to read and understand.
This implementation below is not the most efficient but you can read the code, starting by main() and understand what's being done line by line. If there's any issue you can debug and test each function separately and make sure it covers all you use-cases.
Also, this implementation contains several advanced topics such as java 8 streams, intStreams, splitting string using regex. Some basic error handling to skip whatever the user inputs if is not parseable to Integer.
And it's important to remember: it's better to write readable and maintainable code rather than high-performing obfuscated code. If you need to iterate a list twice but it'll make the code clear, do it. If you know the list might have +1K elements, optimise.
public class Exercise {
public String getUserInput() {
//Implementation is left to you.
return myString;
}
// https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space
private List<String> splitStringBySpace(String input) {
return Arrays.asList(input.split("\\s+"));
}
private List<Integer> convertListToIntegers(List<String> input) {
return input.stream().map(str -> {
try {
return Integer.parseInt(str);
} catch (NumberFormatException ex) {
//Skip whatever is not parseable as a number
return null;
}
}).filter(Objects::nonNull)
.collect(Collectors.toList());
}
private Integer sumList(List<Integer> input) {
/* Alternative solution
int acum = 0;
for (int i = 0; i < input.size(); i++) {
acum += input.get(i);
}
return acum;
*/
return input.stream().mapToInt(i -> i).sum();
}
public static void main() {
String inputText = getUserInput();
System.out.println("User has entered: " + inputText);
List<String> listOfNumbersAsString = splitStringBySpace(inputText);
List<Integer> listOfNumbers = convertListToIntegers(listOfNumbersAsString);
Integer myResult = sumList(listOfNumbers);
System.out.println("Total = " + myResult);
}
}

2d array size based on input

I have a code where in, an array is to be defined, in which the size is based on user input. How do I do that?
My code is as follows:
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of layers in the network:");
int Nb_Layers = in.nextInt();
int[] Hidden_layer_len = new int[Nb_Layers];
for (int i = 0; i < Nb_Layers-1; i++)
{
System.out.println("Enter the length of layer" +(i+1)+":");
Hidden_layer_len[i] = in.nextInt();
if(i == 0)
{
double [][] E = new double[Hidden_layer_len[i]][1];//This is the array I need based on the size mentioned.
}
}
System.out.println(E);
}
I want this to be a 2D array. Any suggestions would be appreciated. thank you!
You can define the array outside the for loop and assign inside. E.g.
double[][] E = null;
for (int i = 0; i < Nb_Layers - 1; i++) {
System.out.println("Enter the length of layer" + (i + 1) + ":");
Hidden_layer_len[i] = in.nextInt();
if (i == 0) {
E = new double[Hidden_layer_len[i]][1];
}
}
This way it will be available when you print it at the end.
By the way you probably want to print it like this
System.out.println(Arrays.deepToString(E));

Delete Method without Array List

I need to implement a delete method WITHOUT USING AN ARRAY LIST. I need to use a set of loops to do it. Here is my delete method and add method as well as any other important variables used. Any advice on what is wrong with my code would be great.
EDITED: Changed the comparing of references to values. Seems to work repeatedly.
final int MAX_DEVICES = 5;
// Array of devices
private Device list[] = new Device[MAX_DEVICES];
// Number of Devices currently in the list
// "Valid" Devices are stored in cells 0 - (numDevices - 1)
private int numDevices = 0;
Scanner stdin; // read from stdin
private void Add()
{
String thisName;
int numThisRead;
float thisInitVal;
thisName = stdin.next();
numThisRead = stdin.nextInt();
thisInitVal = stdin.nextFloat();
if(numDevices > MAX_DEVICES)
System.out.println("The List was full. " + thisName +
" was not added to the list.");
else
{
Device myDevice = new Device(thisName, numThisRead, thisInitVal);
list[numDevices] = myDevice;
numDevices ++;
System.out.println(thisName + " device has been added to the list.");
}
}
private void Delete() //ASK QUESTION
{
String thisDelete;
thisDelete = stdin.next();
for(int i = 0; i < MAX_DEVICES; ++i)
{
if(list[i].getName().equals(thisDelete)) //if you find the name
{
System.out.println(list[i].getName() + " was deleted from the "
+ "list.");
for(int j = i; j < numDevices - 1; j++)
list[j] = list[j + 1];
numDevices--;
return;
}
}
System.out.println(thisDelete + " not deleted. It is not in the list.");
}
If you need to avoid using data type List, you can place the objects in the array. Then you can declare an array one element smaller than the current array and copy all the elements, except for the one you want deleted, over into the new array. Then return the new array.

java String index out of bounds error

I'm trying to reverse a sentence. (if the sentence is "i am a cat", then the result should be "cat a am I") The problem is that I'm getting an index out of bounds error, I'm not sure how to fix the problem. Not sure if my index is wrong or if the substring part is wrong. I'm just a beginner in Java, so any help is really appreciated. error: String index out of range: -1
Thanks
public class ReverseWords {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = in.nextLine();
File f = new File(fileName);
try {
Scanner input = new Scanner(f);
int x = 1;
int n = input.nextInt();
while (x<n) {
String line = input.nextLine();
Queue<String> q = new LinkedList<String>();
q.add(line);
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
ArrayList<String> a = new ArrayList<String>();
while (line.length() > 0) {
a.add(word);
q.remove(word);
}
System.out.println("Case #" + x);
for (int i = a.size(); i != 0; i--) {
System.out.print(a.get(i));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
From the Java documentation of String:
public int indexOf(int ch)
...
If no such character occurs in this string, then -1 is returned.
are you prepared for that there is no more whitespace?
For example at the last iteration...
But it looks like there are other bugs, too.
Your problem would be with a line like the following:
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
whenever indexOf doesn't find what it's looking for, it will return -1. If you ever try to use that index on the string, you'll be indexing at -1 which is out of bounds.
it looks like you're trying to find the space in a line that has no space.

Java Dictionary Searcher

I am trying to implement a program that will take a users input, split that string into tokens, and then search a dictionary for the words in that string. My goal for the parsed string is to have every single token be an English word.
For Example:
Input:
aman
Split Method:
a man
a m an
a m a n
am an
am a n
ama n
Desired Output:
a man
I currently have this code which does everything up until the desired output part:
import java.util.Scanner;
import java.io.*;
public class Words {
public static String[] dic = new String[80368];
public static void split(String head, String in) {
// head + " " + in is a segmentation
String segment = head + " " + in;
// count number of dictionary words
int count = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
String word = phraseScan.next();
for (int i=0; i<dic.length; i++) {
if (word.equalsIgnoreCase(dic[i])) count++;
}
}
System.out.println(segment + "\t" + count + " English words");
// recursive calls
for (int i=1; i<in.length(); i++) {
split(head+" "+in.substring(0,i), in.substring(i,in.length()));
}
}
public static void main (String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
System.out.println();
Scanner filescan = new Scanner(new File("src:\\dictionary.txt"));
int wc = 0;
while (filescan.hasNext()) {
dic[wc] = filescan.nextLine();
wc++;
}
System.out.println(wc + " words stored");
split("", input);
}
}
I know there are better ways to store the dictionary (such as a binary search tree or a hash table), but I don't know how to implement those anyway.
I am stuck on how to implement a method that would check the split string to see if every segment was a word in the dictionary.
Any help would be great,
Thank you
Splitting the input string every possible way is not going to finish in a reasonable amount of time if you want to support 20 or more characters. Here's a more efficient approach, comments inline:
public static void main(String[] args) throws IOException {
// load the dictionary into a set for fast lookups
Set<String> dictionary = new HashSet<String>();
Scanner filescan = new Scanner(new File("dictionary.txt"));
while (filescan.hasNext()) {
dictionary.add(filescan.nextLine().toLowerCase());
}
// scan for input
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next().toLowerCase();
System.out.println();
// place to store list of results, each result is a list of strings
List<List<String>> results = new ArrayList<>();
long time = System.currentTimeMillis();
// start the search, pass empty stack to represent words found so far
search(input, dictionary, new Stack<String>(), results);
time = System.currentTimeMillis() - time;
// list the results found
for (List<String> result : results) {
for (String word : result) {
System.out.print(word + " ");
}
System.out.println("(" + result.size() + " words)");
}
System.out.println();
System.out.println("Took " + time + "ms");
}
public static void search(String input, Set<String> dictionary,
Stack<String> words, List<List<String>> results) {
for (int i = 0; i < input.length(); i++) {
// take the first i characters of the input and see if it is a word
String substring = input.substring(0, i + 1);
if (dictionary.contains(substring)) {
// the beginning of the input matches a word, store on stack
words.push(substring);
if (i == input.length() - 1) {
// there's no input left, copy the words stack to results
results.add(new ArrayList<String>(words));
} else {
// there's more input left, search the remaining part
search(input.substring(i + 1), dictionary, words, results);
}
// pop the matched word back off so we can move onto the next i
words.pop();
}
}
}
Example output:
Enter a string: aman
a man (2 words)
am an (2 words)
Took 0ms
Here's a much longer input:
Enter a string: thequickbrownfoxjumpedoverthelazydog
the quick brown fox jump ed over the lazy dog (10 words)
the quick brown fox jump ed overt he lazy dog (10 words)
the quick brown fox jumped over the lazy dog (9 words)
the quick brown fox jumped overt he lazy dog (9 words)
Took 1ms
If my answer seems silly, it's because you're really close and I'm not sure where you're stuck.
The simplest way given your code above would be to simply add a counter for the number of words and compare that to the number of matched words
int count = 0; int total = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
total++
String word = phraseScan.next();
for (int i=0; i<dic.length; i++) {
if (word.equalsIgnoreCase(dic[i])) count++;
}
}
if(total==count) System.out.println(segment);
Implementing this as a hash-table might be better (it's faster, for sure), and it'd be really easy.
HashSet<String> dict = new HashSet<String>()
dict.add("foo")// add your data
int count = 0; int total = 0;
Scanner phraseScan = new Scanner(segment);
while (phraseScan.hasNext()) {
total++
String word = phraseScan.next();
if(dict.contains(word)) count++;
}
There are other, better ways to do this. One is a trie (http://en.wikipedia.org/wiki/Trie) which is a bit slower for lookup but stores data more efficiently. If you have a large dictionary, you might not be able ot fit it in memory, so you could use a database or key-value store like a BDB (http://en.wikipedia.org/wiki/Berkeley_DB)
package LinkedList;
import java.util.LinkedHashSet;
public class dictionaryCheck {
private static LinkedHashSet<String> set;
private static int start = 0;
private static boolean flag;
public boolean checkDictionary(String str, int length) {
if (start >= length) {
return flag;
} else {
flag = false;
for (String word : set) {
int wordLen = word.length();
if (start + wordLen <= length) {
if (word.equals(str.substring(start, wordLen + start))) {
start = wordLen + start;
flag = true;
checkDictionary(str, length);
}
}
}
}
return flag;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
set = new LinkedHashSet<String>();
set.add("Jose");
set.add("Nithin");
set.add("Joy");
set.add("Justine");
set.add("Jomin");
set.add("Thomas");
String str = "JoyJustine";
int length = str.length();
boolean c;
dictionaryCheck obj = new dictionaryCheck();
c = obj.checkDictionary(str, length);
if (c) {
System.out
.println("String can be found out from those words in the Dictionary");
} else {
System.out.println("Not Possible");
}
}
}

Categories

Resources