Opening File Using BufferedWriter - java

I am a beginner to Java; I am trying to append text to a text file that was previously created using the File class and writing to the file using PrintWriter. When I call the first method in my main class the file is created and works. However, when I call the second method "try" is called, but no new text is added to the .txt file. I put the second method into a separate public class but I ran into the same issue. Do I need to initialize the fileName variable again?
Many thanks.
package project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WriteOut {
private int NumberOfMember;
private String ProjectName;
private String[] TeamMember;
public static String fileName;
private int[][] Vote;
public int FirstExport(int NumberOfMember, String ProjectName, String[] TeamMember) {
Scanner scan = new Scanner(System.in);
String fileName="ok"; //initializing the file name
System.out.println("Enter a file name to hold the Project:");
fileName = scan.nextLine( );
File fileObject = new File(fileName+".txt");
while (fileObject.exists( ))
{
System.out.println("There already is a file named "
+ fileName);
System.out.println("Enter a different file name:");
fileName = scan.nextLine( );
fileObject = new File(fileName+".txt");
}
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream(fileName+".txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName +".txt");
System.exit(0);
}
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
outputStream.println("Team Member"+(MemberCount)+ ":"+TeamMember[MemberCount - 1]);
}
outputStream.println("Number of Members:"+ NumberOfMember+ "\nProject Name:"+ProjectName);
outputStream.close();
return NumberOfMember;
}
public int[][] SecondExport(int[][] Vote) {
System.out.println("hello"); //test to see if this is being called correctly
try
{
String content = "This is the content to write into file"; //Test content
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName+".txt", true));
bw.append(content);
System.out.println("Done"); //Test to see if this is being called
bw.flush();
bw.close();
} catch (IOException e)
{
e.printStackTrace();
}
return Vote;
}
}
My main class calls the WriteOut class under the EnterVotes() method:
package project:
import java.util.Scanner; //Importing the scanner tool
import java.util.stream.IntStream; //for summing arrays
import java.io.FileNotFoundException;
import java.text.DecimalFormat; //Importing the decimal tool
public class Project
{
public static void main(String[] args)
{
Project run = new Project();
run.StartMenu();
}
public static String option; //Declaring the strings representing the menu option buttons
private static int NumberOfMember; //Entering the number of members
public static int index=NumberOfMember; //used for later, declaring a square matrix
public static String[] TeamMember; //Declaring the strings representing the names of the members
public static int[][] Vote;
public static String ProjectName; // Declaring the project name variable as a string
private static boolean CorrectInput, ShowMenu; //Booleans CorrectInput, which determines whether the user has entered a valid input and ShowMenu, which determines whether the main menu is displayed again
public String fileName;
static Scanner scan = new Scanner(System.in); // Importing the scanner tool
DecimalFormat twoDecPlcFormatter = new DecimalFormat("0.00"); //Although not used currently, having a decimal formatter could come in handy later
//----------------------------------------------
//Declaration of StartMenu(): listing Menu Options and equalsIgnoreCase to accept either upper or lower case
//----------------------------------------------
Project(){
}
public void StartMenu()
{
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.print("\nWelcome to Splitit ");
do
{
printMenu();
char input = scan.next().charAt(0); //Asking user to input a character
option = Character.toString(input); //Converting from characters to string
checkInput(option);
}
while (CorrectInput == false || ShowMenu == true); //Run StartMenu() while either the CorrectInput is false or ShowMenu is true
}
//----------------------------------------------
//Declaration of checkInput(String OneInput) method
//----------------------------------------------
private void checkInput(String OneInput)
{
if (OneInput.equalsIgnoreCase("A") == true)
{
About();
}
else if (OneInput.equalsIgnoreCase("C") == true)
{
CreateProjectTitle();
}
else if (OneInput.equalsIgnoreCase("V") == true)
{
EnterVotes();
}
else if (OneInput.equalsIgnoreCase("S") == true)
{
ShowProject();
}
else if (OneInput.equalsIgnoreCase("Q") == true)
{
Quit();
}
else
{
System.out.print("\tIncorrect input. "); //If the user has entered an incorrect input, force them to enter in correct input
CorrectInput = false;
}
}
private void printMenu()
{
System.out.println("\n\n\tAbout\t\t(A)");
System.out.println("\tCreate Project\t(C)");
System.out.println("\tEnter Votes\t(V)");
System.out.println("\tShow Project\t(S)");
System.out.println("\tQuit\t\t(Q)");
System.out.print("\n\tPlease choose an option: ");
}
//----------------------------------------------
//Declaration of About() method
//----------------------------------------------
public void About()
{
System.out.println("\tThis is a program designed to assign grades for a project based on each member's \n \tparticipation. ");
}
//----------------------------------------------
//Declaration of ShowProject()
//----------------------------------------------
public void ShowProject()
{
CorrectInput = true;
ShowMenu = true;
StoreVariables getThings = new StoreVariables();
System.out.println("Number of members: " + getThings.getNumberofMember(NumberOfMember));
System.out.println("Project name: " + getThings.getProjectName(ProjectName));
String[] abc = getThings.getTeamMember();
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Name of member " + Counter + " : " + getTeamMemberName(Counter));
}
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Votes for Member " + TeamMember[Counter-1] + " : ");
System.out.print(getThings.getVotes(Vote));
}
}
//----------------------------------------------
//Declaration of EnterVotes()
//----------------------------------------------
public int[][] EnterVotes()
{
CorrectInput=true;
Vote = new int [NumberOfMember][index];
index=NumberOfMember;
if (NumberOfMember==0) {
System.out.println("Please Create a Project Before Entering Votes!"); //Error Message
ShowMenu=true;
}
for (int row=0; row < Vote.length; row++)
{
System.out.println("Enter "+ TeamMember[row]+"'s votes, points must add up to 100:");
System.out.println();
for (int col=0; col < Vote[row].length; col++)
{
System.out.println("Enter "+TeamMember[row]+ "'s points for"+ TeamMember[col]+":");
Vote[row][col] = scan.nextInt();
}
}
//if (sum!=100){
//System.out.println("Error. Please make sure all votes add up to 100.");
//EnterVotes();
//}
sumRow(Vote, NumberOfMember);
return Vote;
}
public int[] sumRow(int[][] Vote, int NumberOfMember)
{
int sum[] = new int[NumberOfMember];
for (int i = 0; i < Vote.length; i++){
int total = 0;
for (int j = 0; j < Vote[0].length; j++)
total +=Vote[i][j];
sum[i] = total;}
for(int i = 1; i < sum.length; i++)
{
if (sum[i] != 100) {
System.out.println("Please Make Sure the points add to 100!");
EnterVotes();
}
}
WriteOut getsecond = new WriteOut();
getsecond.SecondExport(Vote);
return sum;
}
//----------------------------------------------
//Declaration of CreateProject()
//----------------------------------------------
public String CreateProjectTitle()
{
CorrectInput = true;
ShowMenu = true; //Still show Menu
System.out.print("\n\tEnter the project name: "); //Asking user for a project name
ProjectName = scan.next();
CreateProjectNumberofMembers(); //calling methods within the resulting methods
CreateProjectNamesofMembers();
return ProjectName;
}
public int CreateProjectNumberofMembers(){ //ENTER NUMBER OF TEAM MEMBERS
System.out.print("\tEnter the number of team members: "); //Asking user to input a number for all members count
NumberOfMember = scan.nextInt();
System.out.print("\n");
return NumberOfMember;
}
public String[] CreateProjectNamesofMembers(){
TeamMember = new String[NumberOfMember];
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
System.out.print("\tEnter the name of team member " + MemberCount + ": ");
TeamMember[MemberCount - 1] = scan.next();
}
WriteOut getThings2= new WriteOut();
getThings2.FirstExport(NumberOfMember, ProjectName, TeamMember);
System.out.print("Press any key to return to the main menu: ");
String DummyInput = scan.next(); //This is a dummy variable where the input is never used again
ShowMenu = true; //Irrespective of the input, the menu will be shown again by assigning this boolean to tr
return TeamMember;
}
//----------------------------------------------
//Declaration of Quit() method
//----------------------------------------------
public void Quit()
{
CorrectInput = true;
ShowMenu = false; //if ShowMenu is false, the program's menu will terminate
//WriteOut();
System.out.println("\tGoodbye. ");
scan.close();
}
//--------------------------------------------------------------------------------
//Declaration of toString() method to check for all variable values when necessary
//--------------------------------------------------------------------------------
private String getNumberOfMember()
{
return Integer.toString(NumberOfMember);
}
private String getProjectName(int NumberOfProjects)
{
return ProjectName;
}
private String getTeamMemberName(int index)
{
return TeamMember[index - 1];
}
}

You have a field in class WriteOut:
public static String fileName;
and then a local variable in FirstExport with the same name:
String fileName="ok"; //initializing the file name
the local variable takes precedence inside FirstExport and the field is null when you get in SecondExport. You'll get what I understand is the expected behaviour if you just delete the local variable declaration.

Delete the local variable in your method FirstExport:
String fileName="ok";
You only want to use your public field
public static String fileName;
so you can access it from both methods.

Related

I'm getting a null pointer exception error and I can't find the source

I'm creating a program where an airport worker can input plane and flight information, after which airport users can print out the plane and flight information that was input. After running the first method startAirportPanel(), and typing 1 into the reader scanner to add plane information, I would get a null pointer exception error after the plane ID and plane capacity are entered.
outcome:
Airport panel
---------------
Choose operation:
[1] Add airplane
[2] Add flight
[x] Exit
1
Give plane ID:
GHUA-HG
Give plane capacity:
22
After typing in 22 here and pressing enter, I would get the null pointer exception.
Here is the object flights:
import java.util.ArrayList;
public class Flights {
public HashMap<String,Integer> plane = new HashMap<String,Integer>();
public HashMap<String,String> flight = new HashMap<String,String>();
public Flights(){
this.plane = plane;
this.flight = flight;
}
public void planeMap(String id, Integer capacity){
plane.put(id, capacity);
}
public void flightMap(String id, String departure, String destination){
String flight1 = departure + "-" + destination;
flight.put(id, flight1);
}
public ArrayList planeList(){
ArrayList<String> keylist = new ArrayList<String>(plane.keySet());
ArrayList<Integer> valuelist = new ArrayList<Integer>(plane.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0 ; i < keylist.size() ; i++){
newlist.add(keylist.get(i) + " (" + valuelist.get(i) + ")");
}
for(int i = 0 ; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public ArrayList flightList(){
ArrayList<String> keylist = new ArrayList<String>(flight.keySet());
ArrayList<String> valuelist = new ArrayList<String>(flight.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0; i < keylist.size(); i++){
newlist.add(keylist.get(i) + " (" + plane.containsKey(keylist.get(i)) + ") " + "(" + valuelist.get(i) + ")");
}
for(int i = 0; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public int planeInfo(String id){
if(plane.containsKey(id)){
return plane.get(id);
}
return 0;
}
}
And here is the userinterface:
import java.util.HashMap;
import java.util.Scanner;
import java.util.ArrayList;
public class UserInterface {
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
public void startFlightService(){
System.out.println("Flight service ");
System.out.println("--------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[x] Print Quit");
if(reader.equals("x")){
break;
}
if(Integer.parseInt(reader.nextLine()) == 1){
printPlane();
}
if(Integer.parseInt(reader.nextLine()) == 2){
printFlight();
}
if(Integer.parseInt(reader.nextLine()) == 3){
printPlaneInfo();
}
else continue;
}
}
public void startAirplanePanel(){
System.out.println("Airport panel");
System.out.println("---------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[x] Exit");
String input = reader.nextLine();
if(Integer.parseInt(input) == 1){
addPlane();
} if(Integer.parseInt(input) == 2){
addFlight();
}
if(input.equals("x")){
break;
}
}
}
public void addPlane(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
fly.planeMap(id,capacity);
}
public void addFlight(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String departure = reader.nextLine();
System.out.println("Give destination airport code: ");
String destination = reader.nextLine();
fly.flightMap(id,departure,destination);
}
public void printPlane(){
for(int i = 0; i < fly.planeList().size(); i++){
System.out.println(fly.planeList());
}
}
public void printFlight(){
for(int i = 0; i < fly.flightList().size(); i++){
System.out.println(fly.flightList());
}
}
public void printPlaneInfo(){
System.out.print("Give plane ID: ");
String id = reader.nextLine();
System.out.println(id + " (" + fly.planeInfo(id) + ")");
}
}
Lastly, the main class to start the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Write your main program here. Implementing your own classes will be useful.
Scanner reader = new Scanner(System.in);
Flights flightss = new Flights();
UserInterface hello = new UserInterface();
hello.startAirplanePanel();
}
}
```
This part of your constructor makes no sense:
this.fly = fly;
this.reader = reader;
the reader already is instantiated, so you just replace the current value with: the current value.
The fly, however, isn't instantiated. So, you are just setting null to null.
Whatever call you make on fly, will cause an NPE.
Remove the this.reader = reader; and change the line about fly with an actual instantiation.
EDIT:
So, your constructor should be something like:
public UserInterface(){
this.fly = new Flights();
}
I would also re-check your Flights constructor.
The part of the code that is problematic is ( in the UserInterface class ):-
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
Only fly variable type (Flights) is declared without any assignment of the Flights class object.
Fix this using the 'new' keyword for instantiation of the Flights class:-
private Flights fly = new Flights();
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
However code can be refactored in a better way as suggested by #Stultuske.

Name output shows "null" Java

I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();

End of File Error in File Handling Program

I am creating a database project in java using file handling. The program is working without compiling error. Following points are not working
File is storing only first record. (if program is running again it is overwriting file)
I want to display all records but the only first record is displaying with Exeception
Please offer suggestions..
import java.io.*;
public class Student implements Serializable
{
private int roll;
private String name; //To store name of Student
private int[] marks = new int[5]; //To store marks in 5 Subjects
private double percentage; //To store percentage
private char grade; //To store grade
public Student()
{
roll = 0;
name = "";
for(int i = 0 ; i < 5 ; i++)
marks[i] = 0;
percentage = 0;
grade = ' ';
}
public Student(int roll , String name ,int[] marks)
{
setData(roll,name,marks);
}
public void setData(int roll , String name ,int[] marks)
{
this.roll = roll;
this.name = name;
for(int i = 0 ; i < 5 ; i++)
this.marks[i] = marks[i];
cal();
}
//Function to calculate Percentage and Grade
private void cal()
{
int sum = 0;
for(int i = 0 ; i < 5 ;i++)
sum = sum + marks[i];
percentage = sum/5;
if(percentage>85)
grade = 'A';
else if(percentage > 70)
grade = 'B';
else if (percentage >55)
grade = 'C';
else if (percentage > 33)
grade = 'E';
else
grade = 'F';
}
public char getGrade() { return grade; }
public double getPercentage() { return percentage; }
#Override
public String toString()
{
string format = "Roll Number : %4d, Name : -%15s "
+ "Percentage : %4.1f Grade : %3s";
return String.format(format, roll, name, percentage, grade);
}
}
second file
import java.io.*;
public class FileOperation
{
public static void writeRecord(ObjectOutputStream outFile, Student temp)
throws IOException, ClassNotFoundException
{
outFile.writeObject(temp);
outFile.flush();
}
public static void showAllRecords(ObjectInputStream inFile)
throws IOException, ClassNotFoundException
{
Student temp = new Student();
while(inFile.readObject() != null)
{
temp = (Student)inFile.readObject();
System.out.println(temp);
}
}
}
main file
(only two options are working)
import java.util.*;
import java.io.*;
public class Project
{
static public void main(String[] args)
throws IOException,ClassNotFoundException
{
ObjectInputStream inFile;
ObjectOutputStream outFile;
outFile = new ObjectOutputStream(new FileOutputStream("info.dat"));
inFile = new ObjectInputStream(new FileInputStream("info.dat"));
Scanner var = new Scanner(System.in) ;
int roll;
String name;
int[] marks = new int[5];
int chc = 0;
Student s = new Student();
while(chc != 6)
{
System.out.print("\t\tMENU\n\n");
System.out.print("1.Add New Record\n");
System.out.print("2.View All Records\n");
System.out.print("3.Search a Record (via Roll Number) \n");
System.out.print("4.Delete a Record (via Roll Number) \n");
System.out.print("5.Search a Record (via Record Number)\n");
System.out.print("6.Exit\n");
System.out.print("Enter your choice : ");
chc = var.nextInt();
switch(chc)
{
case 1:
System.out.print("\nEnter Roll number of Student : ");
roll = var.nextInt();
System.out.print("\nEnter Name of Student : ");
name = var.next();
System.out.println("\nEnter marks in 5 subjects \n");
for(int i = 0 ; i < 5 ; i++)
{
System.out.print("Enter marks in subject " + (i+1) + " ");
marks[i] = var.nextInt();
}
s.setData(roll , name , marks );
System.out.println("\n Adding Record to file \n");
System.out.printf("Record \n " + s);
System.out.println("\n\n");
FileOperation.writeRecord(outFile,s);
System.out.println("Record Added to File\n ");
break;
case 2:
System.out.println("All records in File \n");
FileOperation.showAllRecords(inFile);
break;
default: System.out.println("Wrong choice ");
}
}
outFile.close();
inFile.close();
}
}
Your program found a ClassNotFoundException and your method only throws an IOException.
I would check your import statements to make sure you are bringing in the class for ObjectInputStream
import java.io.ObjectInputStream;
If you want to get rid of unreported exception try:
Try
public static void showAllRecords(ObjectInputStream inFile) throws IOException, ClassNotFoundException

Running a loop again and passing the control to Main class in Java after output

I am trying to make a simple JAVA program that will help a user select a car of his choice.
public class CarSelector {
static CarSelector start = new CarSelector();
public String BodyType(String a){
String hatchBack, SUV, MUV, compactSedan, sedan, saloon, miniVan, convertible, hybrid, coupe;
if(a.equalsIgnoreCase("a")){
hatchBack = "polo";
System.out.println("We recommend: " +hatchBack);
}
String b = "";
if(a.equalsIgnoreCase("b")){
SUV = "Fortuner";
System.out.println("We recommend: " +SUV);
}
if(a.equalsIgnoreCase("c")){
compactSedan = "Amaze";
System.out.println("We recommend: " +compactSedan);
}
if(a.equalsIgnoreCase("d")){
sedan = "Vento";
System.out.println("We recommend: " +sedan);
}
if(a.equalsIgnoreCase("e")){
saloon = "Corolla";
System.out.println("We recommend: " +saloon);
}
if(a.equalsIgnoreCase("f")){
MUV = "Innova";
System.out.println("We recommend: " +MUV);
}
else{
System.out.println("Incorrect choice.");
System.out.println(a);
//start.BodyType(a);
return null;
}
System.out.println("We recommend: " +a);
return null ;
}
public int PriceRange(){
int price5 = 5;
int price10 = 10;
int price15 = 15;
int price20 = 20;
int price25 = 25;
int price30 = 30;
return 0 ;
}
public String SegmentBest(){
//string type of the best cars within price range
return null;
}
public int OnRoadPrice(){
//return int of on road price
return 0;
}
public String Manufacturer(){
//all manufacturers with their models available
String Toyota, Volkswagen, Honda;
String i1= "Toyota";
String i2= "Volkswagen";
String i3= "Honda";
return null;
}
public int SeatingCapacity(){
//return integer seating capacity
return 0;
}
public String ReviewLink(){
return null;
}
public String LatestReleases(){
return null;
}
public String FuelType(){
return null;
}
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
option = input.nextLine();
if( option.equalsIgnoreCase("a")){
System.out.println("A: Hatchback");
System.out.println("B: SUV");
System.out.println("C: MUV");
System.out.println("D: Sedan");
System.out.println("E: Saloon");
System.out.println("F: Compact Sedan");
String optionA = input.nextLine();
start.BodyType(optionA);
}
}
}
The code is simple. A walkthrough: The main class will prompt the user to make a choice of how he wants to choose a car. Given option "A" as a choice will run the first method. Here are my queries
Within the BodyType method, I would like to run the set of IF statements again if the user enters anything other than a,b,c,d,e,f
How can I hand the control back to the main class (run a specific code from MAIN method) and also start a method from another method (from BodyType to PriceRange). I hope I was clear. Thanks, Cheers!
you can play it now...
import java.util.Scanner;
public class CarSelector {
static CarSelector start = new CarSelector();
static String[] bodytypes = new String[]{"hatchBack", "SUV", "MUV", "compactSedan", "sedan",
"saloon", "miniVan", "convertible", "hybrid", "coupe"};
static String[] manufacturers = new String[]{"Toyota", "Volkswagen", "Honda"};
private String getBodyType(int bt) {
if(bt >= bodytypes.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + bodytypes[bt]);
return bodytypes[bt];
}
}
public static String getManufacturer(int mf) {
if(mf >= manufacturers.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + manufacturers[mf]);
return manufacturers[mf];
}
}
public static void main(String[] args) {
String bodyType = "";
String manufacturer = "";
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
pringSelectType();
option = input.nextLine();
while(!option.equalsIgnoreCase("o")){
if (option.equalsIgnoreCase("a")) {
for(int a = 0; a < bodytypes.length ; a++){
System.out.println(a+": "+ bodytypes[a]);
}
option = input.nextLine();
bodyType = start.getBodyType(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else if (option.equalsIgnoreCase("b")) {
for(int a = 0; a < manufacturers.length ; a++){
System.out.println(a+": "+ manufacturers[a]);
}
option = input.nextLine();
manufacturer = getManufacturer(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else{
option = input.nextLine();
System.err.println(("input a right choice"));
pringSelectType();
option = input.nextLine();
}
}
System.out.println("");
System.out.println("it's your choice below: ");
System.out.println("bodyType : "+ bodyType);
System.out.println("manufacturer : "+ manufacturer);
}
private static void pringSelectType() {
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
}
}
i delete some unused method,and change some code.
i don't make any note,cause i think it's easy enough..
if u have some problem,comment it,i will see.
PS:when u want to over the select system,input o.it will be done.

Formatting output method

I have a question with the display array method. I can't figure how to make it to format this:
Credit Card # 4:
8908 9014 8812 1331
What I need to do is for each array element call the display method and pass the index of the array in a string for the label, I just cant figure out how to do this, I tried this but it is wrong:
System.out.println(display("Credit Card # %d", cred1[i]));
Can anyone please suggest a way to do this?
package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{ CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother();
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray()
{
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1)
{
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
System.out.print(tempArray.length);
for(int i = 0; i < tempArray.length; i++)
{
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1)
{
for(int i = 0; i< cred1.length; i++)
{
System.out.println(display("Credit Card # %d", cred1[i]));
}
}
public static boolean TryAnother()
{
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
{
return true;
}
return false;
}
}
sounds like all you need is a new line character. For example.
System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());
The new line character "\n" will drop the output onto it's own line.
Do this:
System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());

Categories

Resources