Could I get some help understating what is causing my "NoSuchElementException"? - java

I am currently going through the Helsinki MOOC for Java OOP and I have hit a snag on one of the questions. I am working on Week 7 Exercise 8 and when I run my code manually I am getting everything to work out okay. However when I run their automated tests I am getting the "NoSuchElementException" error.
It is my understanding from the JavaDoc on this particular error that it is most likely caused by .nextLine() not finding a line to read. What confuses me though is based on the error message, and the location of the exceptions, my use of .nextLine() is working in some places and not others while I am using it in the same manner. I included my class that I am using below. Thanks for the help everyone, and if I overlooked a previous post similar to this I apologize.
import java.util.Scanner;
import java.util.ArrayList;
public class AirportPanel {
private Scanner reader;
private ArrayList<Airplane> airplanes;
private ArrayList<Flight> flights;
public AirportPanel(Scanner reader){
this.reader = reader;
this.airplanes = new ArrayList<Airplane>();
this.flights = new ArrayList<Flight>();
}
public void start(){
System.out.println("Airport panel");
System.out.println("--------------------\n");
while(true){
printMenu();
String input = readString();
if(input.toLowerCase().equals("x")){
break;
}else{
chooseOperation(input);
}
}
}
private void printMenu(){
System.out.println("Choose operation:");
System.out.println("[1] Add airplane" + "\n[2] Add flight" + "\n[x] Exit");
System.out.print("> ");
}
private void chooseOperation(String input){
if(input.equals("1")){
addPlane();
}else{
addFlight();
}
}
private void addPlane(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give plane capacity: ");
String planeCap = readString();
this.airplanes.add(new Airplane(planeID, planeCap));
}
private void addFlight(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give departure airport code: ");
String airport1 = readString();
System.out.print("Give destination airport code: ");
String airport2 = readString();
String airports = airport1 + "-" + airport2;
for(Airplane ap : this.airplanes){
if(ap.getID().equals(planeID)){
this.flights.add(new Flight(ap, airports));
}
}
}
private String readString(){
return this.reader.nextLine();
}
EDIT: Here is a screenshot of the stack trace. I also made a github repo with all of my files in the event that would help more. I am pretty new to coding so excuse the mess I surely made of these files.
EDIT 2: I went to my readString() method and changed my call of .nextLine() to .next() and it fixed my issue. I'm not entirely sure how or why but it is now submitting correctly.

Related

Is there a way to implement some gui (message box that asks for multiple inputs ie. registration document) into a code ive written

I just want a simple popup message box that asks for multiple inputs and such.
System.out.println("Please enter Name");
Name = name.nextLine();
System.out.println("Please enter Age");
age=ages.nextInt();
System.out.println("Please enter Gender");
Gender =gender.nextLine();
System.out.println("Please enter Contact Number");
ConNum =number.nextLine();-->
Is there a way to make a gui for this? (its a foundation level project)
Use JOptionPane to take your input:
String name = JOptionPane.showInputDialog(null, "Please enter Name");
Edit:
You could ask the user all the questions on the one box (for this example, ensure they separate the answers by a space).
String input = JOptionPane.showInputDialog(null, "Please enter name.\nPlease enter age.\nPlease enter gender.");
String[] allInput = input.split("\\s+");
System.out.println("Name: " + allInput[0] + " Age: " + allInput[1] + " Gender: " + allInput[2]);
Note: obviously there will be issues, such as not using a space, or using a full name (Jack Sparrow) etc; but it gives you a general idea.
As #notyou mentioned you can use JOptionPane it's very simple to implement it into you code check this example :
import java.io.*;
import javax.swing.*;
public class SystemOutDialog {
public static void main(String[] args) {
// set up a custom print stream
CustomPrintStream printStream = new CustomPrintStream();
System.setOut(printStream);
// from now on, the System.out.println() will shows a dialog message
System.out.println("hello!");
System.out.println("how are you?");
}
}
class CustomPrintStream extends PrintStream {
public CustomPrintStream() {
super(new ByteArrayOutputStream());
}
public void println(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
}
Source link

How do I return the number of items found after I do a search?

Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.

Exception in thread "main" java.util.NoSuchElementException: No line found

details:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine<Scanner.java:1540>
at CarReader2.main<CarReader2.java:30>
that's the entirety of the error.
My code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CarReader2 {
String name, speed, acc;
public CarReader2(String carName, String carSpeed, String carAcc){
name = carName;
speed = carSpeed;
acc = carAcc;
}
public String toString(){
return "Name of car: " +name+ "\nSpeed of car: " +speed+"\nAcceleration of car: " +acc+"\n";
}
public static void main(String[] args) {
File file = new File("carlist.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String c1Name = sc.nextLine();
String c1Speed = sc.nextLine();
String c1Acc = sc.nextLine();
CarReader2 car1 = new CarReader2(c1Name,c1Speed,c1Acc);
car1.speed = c1Speed;
car1.acc = c1Acc;
String c2Name = sc.nextLine();
String c2Speed = sc.nextLine();
String c2Acc = sc.nextLine();
CarReader2 car2 = new CarReader2(c2Name,c1Speed,c1Acc);
car2.speed = c2Speed;
car2.acc = c2Acc;
System.out.println("Information on both cars");
System.out.println("First car:");
System.out.println(car1.toString());
System.out.println("Second car:");
System.out.println(car2.toString());
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
It's supposed to read data of 2 cars from a file called carlist.txt, then print the data of both cars in the correct format.
carlist.txt is a text file containing:
jonathan 3 7
dio 8 2
And the program is supposed to print out,
Information on both cars
First car:
Name of car: jonathan
Speed of car: 3
Acceleration of car: 7
Second car:
Name of car: dio
Speed of car: 8
Acceleration of car: 2
The program compiles but doesn't run correctly and shows the error i posted at the very top.
You're using nextLine method wrong. Name, speed and acceleration are in the same line, but you're using 3 nextLine methods to read them. That's what happens when you try to read 6 lines from a file that only has 2 lines in it. use sc.next() instead of sc.nextLine().
You are reading too many lines. There are only two lines in your file, but you are trying to read 6. You can change your text file to:
jonathan
3
7
dio
8
2
or you can read one line and split out the information you want.

Parser using Scanner not working for "#" sign

Im trying to parse an input file as follows:
#*Nonmonotonic logic - context-dependent reasoning.
##Victor W. Marek,Miroslaw Truszczynski
#t1993
#cArtificial Intelligence
#index3003478
#%3005567
#%3005568
#%3005569
#!abstracst
#*Wissensrepräsentation und Inferenz - eine grundlegende Einführung.
##Wolfgang Bibel,Steffen Hölldobler,Torsten Schaub
#t1993
#cArtificial Intelligence
#index3005557
#%3005567
#!abstracts2
Im creating the parser for this file and Im looking for an output as follows:
Title: Nonmonotonic logic - context-dependent reasoning.
Author: Victor W. Marek,Miroslaw Truszczynski
Year: 1993
Domain: Artificial Intelligence
Index: 3003478
Citation: 3005567
Citation: 3005568
Citation: 3005569
Abstract: Abstract
Title: Wissensrepräsentation und Inferenz - eine grundlegende Einführung.
Author: Wolfgang Bibel,Steffen Hölldobler,Torsten Schaub
Year: 1993
Domain: Artificial Intelligence
Index: 3005557
Citation: 3005567
Abstract: Abstract2
The code that I create so far is below but it produced a totally different output that what I expected and I could not figure out why the scanner reads it the wrong way. It seems to only read the first character of each line as title, not the first line of every part.
Im thinking that maybe the scanner would not read the "#" sign but I guess I might be wrong as well. To make it clear whats wrong, for example, if I only wanna print out the title, the output I got is
Title:*
Title:#
Title:t
Title:c
Title:i
Title:%
Title:!
Title:
Title:*
Title:#
Title:t
Title:c
Title:i
Title:i
Title:%
Title:!
Title:
Done.
And if I tried to print out title and author the output I got is as follows:
Title:*
Author:Nonmonotonic logic - context-dependent reasoning.
Title:#
Author:Victor W. Marek,Miroslaw Truszczynski
Title:t
Author:1993
Title:c
Author:Artificial Intelligence
Title:i
Author:ndex3003478
Title:%
Author:
Title:!
Title:
Author:
Title:*
Author:Wissensrepr?sentation und Inferenz - eine grundlegende Einf?hrung.
Title:#
Author:Wolfgang Bibel,Steffen H?lldobler,Torsten Schaub
Title:t
Author:1993
Title:c
Author:Artificial Intelligence
Title:i
Author:ndex3005557
Title:i
Author:ndex3005557
Title:%
Author:
Title:!
Title:
Author:
Done.
The code is as follows:
import java.sql.*;
import java.util.Scanner;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Citation{
public static void main (String[] args) throws SQLException,
ClassNotFoundException, IOException{
Citation parser = new Citation("D:/test.txt");
parser.processLineByLine();
log("Done.");
}
public Citation(String aFileName){
fFilePath = Paths.get(aFileName);
}
public final void processLineByLine() throws IOException {
try (Scanner scanner = new Scanner(fFilePath, ENCODING.name())){
while (scanner.hasNextLine()){
processLine(scanner.nextLine());
}
}
}
protected void processLine(String aLine){
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("\n");
while(scanner.hasNext()){
// Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("#*");
if(scanner.hasNext()){
String title = scanner.next();
System.out.println("Title:" + title);
}
// Scanner scanner3 = new Scanner(aLine);
scanner.useDelimiter("##");
if(scanner.hasNext()){
String author = scanner.next();
// System.out.println(author);
}
// Scanner scanner4 = new Scanner(aLine);
scanner.useDelimiter("#t");
if(scanner.hasNext()){
String year = scanner.next();
// System.out.println(year);
}
// Scanner scanner5 = new Scanner(aLine);
scanner.useDelimiter("#c");
if(scanner.hasNext()){
String domain = scanner.next();
// System.out.println(domain);
}
// Scanner scanner6 = new Scanner(aLine);
scanner.useDelimiter("#index");
if(scanner.hasNext()){
String index = scanner.next();
// System.out.println(index);
}
// Scanner scanner7 = new Scanner(aLine);
scanner.useDelimiter("#%");
if(scanner.hasNext()){
String cite = scanner.next();
// System.out.println(cite);
}
// Scanner scanner8 = new Scanner(aLine);
scanner.useDelimiter("#!");
if(scanner.hasNext()){
String abstracts = scanner.next();
// System.out.println(abstracts);
}
}
}
// PRIVATE
private final Path fFilePath;
private final static Charset ENCODING = StandardCharsets.UTF_8;
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
}
When I changed the "#*" delimiter as "#//*" delimiter, the title read, but then every line is read as titles as well. It does not detect my other delimiters. The output I got is as follows:
Title:Nonmonotonic logic - context-dependent reasoning.
Title:##Victor W. Marek,Miroslaw Truszczynski
Title:#t1993
Title:#cArtificial Intelligence
Title:#index3003478
Title:#%
Title:#!
Title:
Title:Wissensrepr?sentation und Inferenz - eine grundlegende Einf?hrung.
Title:##Wolfgang Bibel,Steffen H?lldobler,Torsten Schaub
Title:#t1993
Title:#cArtificial Intelligence
Title:#index3005557
Title:#index3005557
Title:#%
Title:#!
Title:
Assuming the file format isn't changing soon, modify as below
protected void processLine(String aLine) {
if (aLine.trim().equals("")) {
System.out.println();//executed when an empty line is read
}
else if (aLine.startsWith("#*")) {
System.out.println("Title:" + aLine.substring(2)); //or, you can also do
//System.out.println("Title:" + aLine.substring("#*".length()));
} else if (aLine.startsWith("otherCases") {
//proceed for other cases in similar fashion.
}
.
.
.
}
The problem is that you are using scanner.useDelimiter("#*");. This method requires a regular expression, where * symbol means zero ore more occurencies of symbol(in your case #). So, use scanner.useDelimiter("#\\*"); in your case.

creating a loop in java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have been struggling to figure out how to make my code loop when asking for user input.
Basically, I want the program to re-ask the question if the user enters no text at all.
This is what I done so far.
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assessment {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String me = JOptionPane.showInputDialog("Please enter your name");
System.out.println("Your name is: " + me);
String user1 = JOptionPane.showInputDialog("Please choose a number");
System.out.println("Your number is: " + user1);
String user2 = JOptionPane.showInputDialog("Please enter your choice of security, choice1(low) or choice2(high)");
String response = (String)System.in.toString();
if(user2.equals("choice1"))
JOptionPane.showMessageDialog(null,"your username is: "+me+user1,"Your username",JOptionPane.WARNING_MESSAGE);
}
}
while (!me.equals("")) {
}
to compare Strings in Java you have to use equals() and since you don't want it to be equal to empty text you should use the negation in Java.
Hope it helps.
This is all you need to do -
String me = "";
do
{
me = JOptionPane.showInputDialog("Please enter your name");
}while(me.equals(""));
Do it for your other windows too.
Or, just copy paste this code :(
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assessment {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(
System.in));
String me = "";
String user1 = "";
String user2 = "";
do {
me = JOptionPane.showInputDialog("Please enter your name");
} while (me.equals(""));
System.out.println("Your name is: " + me);
do {
user1 = JOptionPane.showInputDialog("Please choose a number");
} while (user1.equals(""));
System.out.println("Your number is: " + user1);
do {
user2 = JOptionPane
.showInputDialog("Please enter your choice of security, choice1(low) or choice2(high)");
} while (user2.equals(""));
String response = (String) System.in.toString();
if (user2.equals("choice1"))
JOptionPane.showMessageDialog(null, "your username is: " + me
+ user1, "Your username", JOptionPane.WARNING_MESSAGE);
}
}
You could use a while loop that refers to what they entered:
like while input = ""{question} or even a do while loop.
See this question:
Goto statements in Java
This may also help:
http://www.tutorialspoint.com/java/java_loop_control.htm
use java.util.Scanner.
Scanner input = new Scanner(System.in);
After prompting for the name, use the following:
String name = input_next();
if (name != null && !("").equals(name)) { //then move next - else go back to the prompt
You can find a great tutorial on this here, specifically the "while" and "do-while" statements.
In short :
while (condition) {
// statements
}
and
do {
// statements
} while (condition);
As long as the condition evaluates to true, the statements will keep getting executed. The difference between while and do-while is the time at which the conditions are evaluated, refer to the tutorial for more information.

Categories