Question: Hello I am getting an error Can only iterate over an array or an instance of java.lang.Iterable on line: for (String s : name )

Hello I am getting an error "Can only iterate over an array or an instance of java.lang.Iterable" on line:

"for (String s : name )"

Im trying to add a name using linkedqueues through scanner in java.

- - - - - ----- - - - - - - - -- -

public class LinkedQueue

{

private class Node

{

String value;

Node next;

Node(String val, Node n)

{

value = val;

next = n;

}

}

private Node front = null;

private Node rear = null;

/** Enqueue Employee **/

public void enqueue(String s)

{

if(rear != null)

{

rear.next = new Node(s,null);

rear = rear.next;

}

else

{

rear = new Node(s,null);

front = rear;

}

}

public boolean empty()

{

return front == null;

}

/** Return the Employee in the front **/

public String peek()

{

if(empty())

throw new EmptyQueueException();

else

return front.value;

}

/** Dequeue Employee **/

public String dequeue()

{

if(empty())

throw new EmptyQueueException();

else

{

String value = front.value;

front = front.next;

if(front==null) rear = null;

return value;

}

}

public String toString()

{

StringBuilder sBuilder = new StringBuilder();

Node p = front;

while (p != null)

{

sBuilder.append(p.value + " ");

p = p.next;

}

return sBuilder.toString();

}

public void add(String employee) {

// TODO Auto-generated method stub

}

}

- - - - - -

public class EmptyQueueException extends RuntimeException {

}

- - - - - - - - -

import java.util.Scanner;

public class Main

{

public static void main(String [] args)

{

String name;

Scanner scan = new Scanner(System.in); //creates scanner

LinkedQueue queue = new LinkedQueue(); //declares linkedlist

/**Add names**/

System.out.println("Add a name:" );

name = scan.next();

queue.add(scan.nextLine());

queue.add(scan.nextLine());

queue.add(scan.nextLine());

System.out.println("Adding names:" );

for (String s : name )

{

System.out.print(s + " ");

queue.enqueue(s);

}

System.out.println(" State of queue is: ");

System.out.println(queue);

/**Remove names**/

System.out.println("Removing 2 names.");

queue.dequeue(); queue.dequeue();

System.out.println("State of queue is: ");

System.out.println(queue);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!