Eclipse " scanner.ensureopen() line not available " [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm learning to work with oriented objects and i'm stuck with this error that throws me eclipse when it arrives to the final of my main class. The thing is that I have a class called Wheel and I want to store the user input related to both back wheels and then the two front wheels, then just display the whole info i stored in console.
It works entirely until it arrives to the last scanner for frontwheels, I write the input in console for it and it throws the " scanner.ensureopen() line not available " error, opening it in another window of eclipse and the program doesn't show me the info of frontwheel and doesn't finish as it should.
Here's my code:
WHEEL CLASS
package com.vehicles.project;
public class Wheel {
private String brand;
private double diameter;
// Wheel Constructor
public Wheel(String brand, double diameter) {
this.brand = brand;
this.diameter = diameter;
}
public String infoWheel() {
return "brand: " + brand + " and diameter: " + diameter;
}
}
MAIN
package com.vehicles.project;
import java.util.Scanner;
import javax.swing.*;
import com.vehicles.project.*;
public class Main_Vehicles_Fase1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your plate, car brand and color");
Car userCar = new Car(sc.nextLine(), sc.nextLine(), sc.nextLine());
System.out.println("Your plate is: " + userCar.plate + ", the brand is " + userCar.brand + " and the colour is "
+ userCar.color);
System.out.println("Enter backwheels brand and diameter");
Wheel userBackWheels = new Wheel(sc.nextLine(), sc.nextDouble());
System.out.println("Your backwheels info --> " + userBackWheels.infoWheel());
System.out.println("Enter frontwheels brand and diameter");
Wheel userFrontWheels = new Wheel(sc.nextLine(), sc.nextDouble());
System.out.println("Your frontwheels info --> " + userFrontWheels.infoWheel());
sc.close();
}

I didn't encountered error OP specified, usually we get this error if we close scanner. Looks like it is not closed in the main class based on OP's code.
scanner.ensureopen() line not available
I encountered different error
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at com.vehicles.project.Main_Vehicles_Fase1.main(Main_Vehicles_Fase1.java:28)
I changed the parsing double logic. can you give a try. OP code is not perfect. I don't want to improve it because it might be a homework.
package com.vehicles.project;
import java.util.Scanner;
public class Main_Vehicles_Fase1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your plate, car brand and color");
Car userCar = new Car(sc.nextLine(), sc.nextLine(), sc.nextLine());
System.out.println("Your plate is: " + userCar.plate + ", the brand is " + userCar.brand + " and the colour is "
+ userCar.color);
System.out.println("Enter backwheels brand and diameter");
Wheel userBackWheels = new Wheel(sc.nextLine(), new Double(sc.nextLine()));
System.out.println("Your backwheels info --> " + userBackWheels.infoWheel());
System.out.println("Enter frontwheels brand and diameter");
Wheel userFrontWheels = new Wheel(sc.nextLine(), new Double(sc.nextLine()));
System.out.println("Your frontwheels info --> " + userFrontWheels.infoWheel());
sc.close();
}
}

Related

Input not converted to string?

I'm just getting started with Java (via an edX class), and one of the assignments is to create a vacation planner program that gathers information from the user. When I run the code in terminal, it works, but the strings "name" and "place" are not displayed correctly. Instead, the lines after the string declarations are displayed as "Nice to meet you + name + where are you traveling to?". Am I missing something that would have the input assigned to "name" displayed in the sentence?
The code below is for 1 of 4 methods that will be in the program. Image of my output:
import java.util.Scanner;
public class projectplanner{
public static void main(String[] args) {
partOne();
partTwo();
partThree();
partFour();
}
public static void partOne() {
[enter image description here][1] Scanner input = new Scanner(System.in);
System.out.print("Welcome to Vacation Planner!");
System.out.print("What is your name?" + "");
String name = input.nextLine();
System.out.println("Nice to meet you " + name + "where are you travelling to?");
String place = input.nextLine();
System.out.println("Great! " + place + " sounds like a great trip.");
}

Payment and print receipt part of a bus ticket system

I have to do the last part of my project which is the payment and receipt part. I'm still clueless of how to do the payment part, but I did try to do the print receipt part. I'm using Netbeans 8.2. The coding below is my print receipt code, it builds successfully but doesn't bear any output. Maybe it's because I have to compile all the other codes like the seat numbers, date, time and all before this could print? Not sure if the reason was because i left the main part empty but I don't know what to put in there tbh.
I'm a beginner coder btw and still have a long long long way to go. I will try my best to understand your explanations. Thank you in advance.
import java.util.Date;
import java.util.Scanner;
public class BusPaymentDetails {
public static void main(String[] args) {
}
class Printpaymentdetails {
public void Printpaymentdetails () {
Date timenow = new Date();
Scanner ticket = new Scanner(System.in);
System.out.println("Your Bus E-Ticket: ");
String date = ticket.nextLine();
System.out.println("Date: " + timenow.toString());
String deptime = ticket.nextLine();
System.out.println("Time of departure: " + deptime);
String arrtime = ticket.nextLine();
System.out.println("Time of arrival: " + arrtime);
String place = ticket.nextLine();
System.out.println("Trip to: " + place);
String buscompany = ticket.nextLine();
System.out.println("Bus Company: " + buscompany);
int seatnumber = ticket.nextInt();
System.out.println("Seat number: " + seatnumber);
double price = ticket.nextDouble();
System.out.println("Price: " + price);
System.out.println("This ticket is non-refundable.");
System.out.println("Please be courteous and do not smoke. Enjoy your trip.");
}
}
}
When running java code, you're invoking a main method, here it is empty, so nothing is run. You would have to add something to the body of this method:
public static void main(String[] args) {
new Printpaymentdetails();
}

How to pass a NumberFormat object to a method?

I'm trying to use a NumberFormat object to display a price. I'm very new to programming, my book isn't very helpful, nor is my teacher. I have a class called Product and a class called MyProduct, which is a subclass of Product. In the Product class there is a method called getPrice() that has no parameters. All it does is return the value for price. My task is to create a method in MyProduct called getPrice(NumberFormat nf) that returns the price, but formatted as currency. In the main method, if I use myproduct.getPrice(); I get the price, but unformatted (I know this is because it's calling getPrice() from Product, not getPrice(NumberFormat nf) from MyProduct. My question is what do I put in as an argument to stop getting a compile time error? I've tried getPrice(nf), getPrice(this), getPrice(price), just about anything I can think of and nothing works. Any help would be greatly appreciated and all relevant lines of code are posted below. Thanks in advance.
Below is the MyProduct class
public class MyProduct extends Product{
public MyProduct()
{
super();
}
NumberFormat nf;
public String getPrice(NumberFormat nf) {
this.nf = NumberFormat.getCurrencyInstance();
String priceFormatted = nf.format(price);
return priceFormatted;
}
And here is ProductApp class
public class ProductApp {
public static void main(String args[]) {
// display a welcome message
System.out.println("Welcome to the Product Viewer");
System.out.println();
// create 1 or more line items
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get input from user
System.out.print("Enter product code: ");
String productCode = sc.nextLine();
// Use a ProductReader object to get the Product object
ProductDB db = new ProductDB();
MyProduct myproduct = db.getProduct(productCode);
// display the output
String message = "\nPRODUCT\n" +
"Code: " + myproduct.getCode() + "\n" +
"Description: " + myproduct.getDescription() + "\n" +
"Price: " + myproduct.getPrice()+ "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
System.out.println("Bye!");
The line I need help with is
"Price: " + myproduct.getPrice()+ "\n";
As you are instantiating nf within your getPrice method then I would not bother passing it. Maybe change the method name to something like getPriceAsString defined as
public String getPriceAsString() {
NumberFormat nf = NumberFormat.getCurrencyInstance(); // keep local
String priceFormatted = nf.format(price);
return priceFormatted;
}
Then you can call it as myProduct.getPriceAsString ()
edit
As per you comment
In main do
"Price: " + myproduct.getPrice(NumberFormat.getCurrencyInstance())+ "\n";
And declare the method as
public String getPrice(NumberFormat nf) {
return nf.format(price);
}
I assume that price is correctly set

How do I run this program in an applet?

package Homework;
import java.util.Scanner;
class FantasyGame{
public static void main ( String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest!");
System.out.println("Enter the name of your character: ");
String name;
name = scan.nextLine();
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest, " + (name) + "! " + "You will now assign attributes to your character, the total value assigned must not exceed 15 or be under 0, or the points will be assigned by default! (Type any NUMBER to continue)");
int ans = scan.nextInt();
System.out.println("Enter Strength (0-15): ");
int str = scan.nextInt();
System.out.println("Enter Health (0-15): ");
int hp = scan.nextInt();
System.out.println("Enter Luck (0-15): ");
int lck = scan.nextInt();
if (str + hp + lck <= 15)
{
System.out.println("Congratulations! You have successfully created your character!");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (str));
System.out.println("Health: " + (hp));
System.out.println("Luck: " + (lck));
}
if (str + hp + lck > 15)
{
System.out.println("You have give your character too many attribute points! Default values have been assigned.");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (5));
System.out.println("Health: " + (5));
System.out.println("Luck: " + (5));
}
}
}
I want to make a text-based game for my history class and I know basic Java enough to make a small one with just variables and stuff but I don't know how I can make it so that it runs directly as an applet with a black background and white text that shows up and responds to what you type, like the code above does in the console.
I've tried the command prompt method but all I get is "Access is Denied."
Also, when I try to export in eclipse, the launch configuration always goes to a class I don't want. Sorry but I am really confused and need a lot of help on this.
to write a simple applet, http://docs.oracle.com/javase/tutorial/deployment/applet/ this tutorial from oracle will walk you through it fairly well, it shouldn't be too hard to rearrange your code then
I figured it out. I just exported my program as a .jar and used Jar2Exe and it worked perfectly. Thanks!
You have not made you class public and that is why you are getting error "Access is denied" because it is not visible any more. Compiler is not able to find that class. Just write
....
//change is here
public class FantasyGame
{
....
}
....
Thanks !

How do I redirect Console Output to GUI Form?

I'm taking a Java programming class at school and we've been working on a project in class - dealing with console applications. For the coming week, we're moving on to working on creating GUI applications with JAVA and I had an idea of what to do with one of my projects.
I wanted to redirect the console output to a text area inside the GUI. But I don't know if this is possible, or how to do it. Is it possible, if so, can somebody help me. I'm trying to design my form so that it looks like a cash register (with the receipt on one side of the register). In this case, the receipt will be the redirected console output.
Any help would be greatly appreciated.
Here's my source code:
package autoshop_invoice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AutoShop_Invoice
{
public static void total_sales() throws IOException
{
String text = "";
String part_number = "";
int num_items = 0;
double price = 0.0;
double tax = 0.0;
double total_sale = 0.0;
//Prompt user for part number and store value in variable part_number.
System.out.println("Enter Part Number then hit enter.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try
{
part_number = in.readLine();
} catch (IOException ex)
{
Logger.getLogger(AutoShop_Invoice.class.getName()).log(Level.SEVERE, null, ex);
}
//Prompt user to enter number of items sold and store value in variable num_items.
System.out.println("Enter Number of Items sold then hit enter.");
in = new BufferedReader(new InputStreamReader(System.in));
text = in.readLine();
num_items = Integer.parseInt(text);
//Prompt user to enter Price per Item and store value in variable num_items.
System.out.println("Enter Price per Item then hit enter.");
in = new BufferedReader(new InputStreamReader(System.in));
text = in.readLine();
price = Double.parseDouble(text);
//Display the total sale WITH tax calculated.
total_sale = num_items * price;
tax = total_sale * .06;
total_sale = total_sale + tax;
//DecimalFormat df = new DecimalFormat("#.##");
NumberFormat nf = NumberFormat.getCurrencyInstance(); //Get the current system locale currency
System.out.println();
System.out.println("***********************************");
System.out.print("Part Number: " + part_number + " "); //Display the Part Number being sold
System.out.println("QTY: " + num_items); //Display the quantity of items sold
System.out.println("Sub-Total is: " + nf.format(total_sale)); //Display sub-total rounded to 2 decimal points
System.out.println("MD Sales Tax due (6%): " + nf.format(tax)); //Display the calculated sales tax
//Display grand-total rounded to 2 decimal points and formatted with the locale currency
//System.out.println("Grand-Total sales is: " + df.format(nf.format(total_sale + tax)));
System.out.println("Grand-Total sales is: " + nf.format(total_sale + tax));
System.out.println("***********************************");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
total_sales();
}
}
Write your own OutputStream implementation that adds any bytes written to the text area. Then wrap it in a PrintStream and pass it to System.setOut():
System.setOut(new PrintStream(myTextAreaOutputStream));
You can use Java Swing to easily create a form and implement its functionality.
Take a look at this tutorial: http://docs.oracle.com/javase/tutorial/uiswing/start/
A walk through on a basic project starts here using Netbeans http://docs.oracle.com/javase/tutorial/uiswing/learn/settingup.html
It's pretty straight forward. Lay out the controls, and then implement the functionality. I think their Celsius converter example will get you very close to finishing your project with just a few modifications.

Categories