Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
Related
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
I am creating a booking project in NetBeans, I am first implementing a booking controller that will validate user input using the Java scanner. I would like to test the code and input data in the terminal. When I run the output of the code terminal the terminal just shows " Build successful". And shows none of the systems out print code line. I am not too sure what is wrong with the code please see below
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner (System.in);
Customer customer = new Customer ();
// customer enter details and the details are validated
private String Customer () {
String customerName = "";
int customerAge = -1 ;
String membership = "";
boolean isName;
System.out.println( "Please enter your name " );
do {
// name of condition HasNext will check the user input
if ( input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
}else
System.out.println ( "You have provided incorrect information");
isName = false;
input.next();
}while ( !isName );
System.out.println(customerName);
return customerName;
}
}
Try this code,
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner(System.in);
// Customer customer = new Customer();
// customer enter details and the details are validated
private String Customer() {
String customerName = "";
int customerAge = -1;
String membership = "";
boolean isName;
System.out.println("Please enter your name ");
do {
// name of condition HasNext will check the user input
if (input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
} else
System.out.println("You have provided incorrect information");
isName = false;
input.next();
} while (!isName);
System.out.println(customerName);
return customerName;
}
public static void main(String[] args) {
BookingController con = new BookingController();
con.Customer();
}
}
if any issue inform.
I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}
I just started to learn Java a few days ago and i wanted to create a program that will create an account,stored it and then if we enter the exact username and password then it will say "login successful".Please don't mind my way of naming the variables and classes.My question is in my "crttacc" class,where i have set up 2 get method to get the un and pa variables.However,in my main method after running the create method in crttacc,the input data seem to gone away and not stored in the un,pa variables as when i try to print them out to check it,it would return "null".I'm a newbie so i'm not quite sure that my question was clear enough and i hope that u guys can help me.You have my gratitude.
Here's my codes:(please don't laugh :D)
import java.util.Scanner;
class crttacc {
String pa;
String un;
void create() {
Scanner unin = new Scanner(System.in);
Scanner passin = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = unin.nextLine();
System.out.println("enter the password: ");
String l2 = passin.nextLine();
l1=un;
l2=pa;
}
String getpass(){
return un;
}
String getuser(){
return pa;
}
}
class loginn {
;
void logingin() {
crttacc acc1 = new crttacc();
String pass = acc1.getpass();
String user = acc1.getuser();
System.out.println(pass);
System.out.println(user);
Scanner passwordinput = new Scanner(System.in);
Scanner usernameinput = new Scanner(System.in);
System.out.println("username:");
String line1 = usernameinput.nextLine();
System.out.println("Password:");
String line2 = passwordinput.nextLine();
String d1=line1;
String d2=line2;
if(d1.equals(pass) && d2.equals(user)) {
System.out.println("login successfull");
}
else {
System.out.println("try again");
}
}
}
public class login3 {
public static void main(String[] args) {
Scanner com = new Scanner(System.in);
System.out.println("enter your command: create account or login");
String com1 = com.nextLine();
String l1=com1;
if(com1.equals("create account")) {
crttacc acc1 = new crttacc();
acc1.create();
}
Scanner com2 = new Scanner(System.in);
System.out.println("would you like to login now? y/n");
String cm2 = com2.nextLine();
String l2=cm2;
if(l2.equals("y")) {
loginn log1 = new loginn();
log1.logingin();
}
else{
}
}
}
it's :
un=l1;
pa=l2;
in the Create() method
The problem seems to be, that you store the input data you get through the scanner in l1 and l2. Then you give your l1 and l2 variables the value of un and pa (which is null at this point). At the end of your method the local variables l1 and l2 are thrown away and nothing changed for your un and pa.
You propably wanted something like this:
void create() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = scanner.nextLine();
System.out.println("enter the password: ");
String l2 = scanner.nextLine();
this.un = l1;
this.pa = l2;
}
With this you stored the values of l1 and l2 in your fields un and pa and can access them through your getters.
Hint: you don't need a new Scanner for every input. You can reuse it :)
My issue is simple. And I am sure the solution is simple too. But my attempts have failed. I looked on every question on here that relates to this but it does not contain the solution I am looking for. I am using a ReadGameFile() method and a WriteToGameFile() method that is in my class VideoGameManager. I have a class that contains a method that outputs data in the following way :
this class is called VideoGameManager
which has a method that is called public void printSearchCriteria(String nameInput,String consoleInput);
name (tab space) platform
name " " platform
name " " platform
....etc.
then in a main class I have a new instance of VideoGameManaer
VideoGameManager vG = new VideoGameManager();
I then call the method that outputs the data with the following parameters
in which the user inputs
nameInput = keyboard.next();
consoleInput = keyboard.next();
vG.printSearchCriteria(String nameInput, String consoleInput);
This results in the data being printed in the way which was stated above.
I now need to find a way to take that output. and store it in new file in which the user will name.
System.out.println("Enter the file name to print out.");
String fileNamePrintToFile = keyboard.next();
//Some way that takes the data from the output of printSearchCriteria and stores it in a new file from the user input -fileNamePrintToFile.
VideoGameManager File
public class VideoGameManager {
Scanner keyboard = new Scanner(System.in);
//array list
private ArrayList<VideoGame> games;
//tab
private static final String delim = "\t";
//constructor
public VideoGameManager(){
games = new ArrayList<VideoGame>();
}
public void ReadGameFile(String fileName)
{
//This reconstructs a new instance of the VideGame array list.
//This is done to clear the array list
games = new ArrayList<VideoGame>();
try
{
//Create a new file Scanner
Scanner fileScanner = new Scanner(new File(fileName));
//Reads each line in the file one-by-one
while(fileScanner.hasNextLine())
{
//Stores the next line of code
String nextLine = fileScanner.nextLine();
//That line is then split using the delimiter (\t)
String[] splitStrings = nextLine.split(delim);
//If the newly created array is not 2 items in length then
//that line is not correctly formatted and should be ignored.
if(splitStrings.length != 2)
continue;
String gameName = splitStrings[0];//The first element is the game name
String console = splitStrings[1];//Next is the console
VideoGame newVideoGame = new VideoGame(gameName,console);
games.add(newVideoGame);//Added to the array list
}
fileScanner.close();
}
catch(Exception e)
{
System.out.println(" File does not exist ");
}
}
public void WriteToGameFile(String fileName, boolean append)
{
if(games == null)//if the file name is null then return
return;
try
{
//Creates the new instance of a print writer
PrintWriter fileWriter = new PrintWriter(new FileOutputStream(fileName,append));
for(VideoGame aVideoGame : games)
{
//Prints to the file
fileWriter.println(aVideoGame.getName()+delim+
aVideoGame.getConsole());
}
fileWriter.close();
}
catch(Exception e)
{
System.out.println("Error");
}
}
//returns an array list of video games based on a search criterion (name and console)
public void PrintSearchCriteria(String nameInput, String consoleInput)
{
for(VideoGame aVideoGame : games)
{
if(aVideoGame.getName().contains(nameInput) == true && aVideoGame.getConsole().contains(consoleInput) == true)
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
else if(aVideoGame.getName().contains(nameInput) == true && consoleInput.equalsIgnoreCase("*"))
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
else if(nameInput.equalsIgnoreCase("*") && aVideoGame.getConsole().contains(consoleInput) == true)
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
}
}
public void PrintCurrentResults(String fileName)
{
for(VideoGame aVideoGame : games)
{
System.out.println(aVideoGame.getName()+delim+
aVideoGame.getConsole());
}
}
}
Main Class
public class VideoGameFrontEnd {
public static void main(String[] args) {
//create and connect scanner object to keyboard
Scanner keyboard = new Scanner(System.in);
VideoGameManager vG = new VideoGameManager();
System.out.println("Welcome to the video game database!");
boolean quit = false;
try{
while(quit == false)
{
System.out.println("Enter 1 to load the video game database");
System.out.println("Enter 2 to search the database");
System.out.println("Enter 3 to print current results");
System.out.println("Enter 4 to print current results to file");
System.out.println("Enter 0 to quit");
int input = keyboard.nextInt();
switch(input){
case 0: input = 0;
System.out.println("Good Bye");
quit = true;
break;
case 1: input = 1;
System.out.println("Enter the file Name");
String fileName = keyboard.next();
vG.ReadGameFile(fileName);
break;
case 2: input = 2;
System.out.println("Enter the name of the game or '*' for all names");
String nameInput = keyboard.next();
System.out.println("Enter the name of the console or '*' for all consoles");
String consoleInput = keyboard.next();
vG.PrintSearchCriteria(nameInput,consoleInput);
break;
case 3: input = 3;
//print current results
break;
case 4: input = 4;
System.out.println("Enter the file name to print out.");
String fileNamePrintToFile = keyboard.next();
System.out.println("Append to file ? True or False");
String appendToFile = keyboard.next();
if(appendToFile.equalsIgnoreCase("true"))
{
vG.WriteToGameFile(fileNamePrintToFile, true);
}
else if(appendToFile.equalsIgnoreCase("false"))
{
vG.WriteToGameFile(fileNamePrintToFile, false);
}
else
{
System.out.println("Incorrect Response, auto shutdown");
System.exit(0);
}
default:
break;
}
}
}
catch(Exception e)
{
System.out.println("error");
System.exit(0);
}
}
}
I suggest logging framework like log4j,slf4j and so on. Or java standard logging utils.
If you want to know, how to save all the outputs send by System.out.print or println, here is one of the way, how you can achieve.
public static void main(String[] args) throws FileNotFoundException {
PrintStream ps = new PrintStream("mylog.log");
System.setOut(ps);
System.out.println(String.format("%s: %s", new Date(),"Application Started"));
System.out.println(String.format("%s: %s", new Date(),"Application Terminated"));
}
And the output will be some thing like this,