so I need to make the following:
when a user types their name in the console then gets prompted for filling in their age, after that it needs to display the name the amount if times their age is. So for example
User input is Mikey
age input is: 4
then console prints:
Mikey
Mikey
Mikey
Mikey
So far I made the following code:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String invoer;
String invoer2;
System.out.print("Fill in your name:");
invoer = br.readLine();
System.out.print("Fill in your age:");
invoer2 = br.readLine();
System.out.print("" + invoer);
System.out.print(" " + invoer2);
}
I'm very new to java so I'm not sure what the problem is nor what the fix could be. I have been searching for such code to see what I'm doing wrong but I can't seem to find any.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String invoer;
String invoer2;
System.out.print("Fill in your name:");
invoer = br.readLine();
System.out.print("Fill in your age:");
invoer2 = br.readLine();
try {
for (int i = 0; i < Integer.parseInt(invoer2); i++) {
System.out.println(invoer);
}
} catch (NumberFormatException e) {
System.out.println("Age should be a number");
e.printStackTrace();
}
System.out.print("" + invoer);
System.out.print(" " + invoer2);
}
You have get number from user's input. This can be done with Integer.parseInt(invoer2). However it can throw NumberFormatException if the input isn't a valid number.
However I would recommend using Scanner.
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String invoer;
String invoer2;
System.out.print("Fill in your name:");
invoer = s.next();
System.out.print("Fill in your age:");
try {
invoer2 = s.nextInt();
for (int i = 0; i < invoer2; i++) {
System.out.println(invoer);
}
} catch (InputMismatchException e) {
System.out.println("It wasn't valid age");
}
System.out.print("" + invoer);
System.out.print(" " + invoer2);
}
You need to use a loop for printing the name once for each year of age. But first, convert the string input for age into an int which can then be used as a boundary for the loop.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String invoer;
int invoer2;
System.out.print("Fill in your name:");
invoer = br.readLine();
System.out.print("Fill in your age:");
invoer2 = Integer.parseInt(br.readLine());
for (int i=0; i < invoer2; ++i) {
System.out.print(invoer);
}
}
Related
I am creating a hospital management system in which I have 2 classes namely AddDoctor and AddPatient which takes the input from user about their details and stores them into their respective files. I now want to create an Appointment class in which I can assign a patient with a certain ID to a doctor with a certain ID which are read from the files. This would be very easy if Java supported multiple inheritance, but since it doesn't, I'm stuck on how I could do this task.
Following is my AddDoctor class
class AddDoctor{
int did;
int dage;
long dphno;
String dname;
String dgender;
String dqualification;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Doctor's Name:");
dname = br.readLine();
Random rand = new Random();
did = rand.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Doctor's Phone Number:");
dphno = Long.parseLong(br.readLine());
System.out.print("Enter Doctor's Age:");
dage = Integer.parseInt(br.readLine());
System.out.print("Enter Doctor's Gender:");
dgender = br.readLine();
System.out.print("Enter Doctor's Qualification:");
dqualification = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("DoctorDetails.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Doctor you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Doctor To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("DoctorDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line+" ");
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("DoctorDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[6];
data=s.split(" ");
for(int i=0;i<6;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
//Class WriteD to Write Doctor Details in a text file where the details are fetched from the Class AddDoctor
class WriteD extends AddDoctor {
void write() {
try(FileWriter fw = new FileWriter("DoctorDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(did + " " + dname + " " + dphno + " " + dage + " " + dgender + " " + dqualification);
}catch(IOException e){
e.printStackTrace();
}
}
};
Following is my AddPatient Class
class AddPatient extends People{
String pillness;
String pregisterdate;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Patient's Name:");
name = br.readLine();
Random rand1 = new Random();
id = rand1.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Patient's Phone Number:");
phno = Long.parseLong(br.readLine());
System.out.print("Enter Patient's Age:");
age = Integer.parseInt(br.readLine());
System.out.print("Enter Patient's Gender:");
gender = br.readLine();
System.out.print("Enter Patient's Illness:");
pillness = br.readLine();
System.out.print("Enter Patient's Registration Date:");
pregisterdate = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("PatientDetails.txt");
File tempFile = new File("myTemp2.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Patient you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Patient To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("PatientDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line);
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("PatientDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[7];
data=s.split(" ");
for(int i=0;i<7;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
class WriteP extends AddPatient {
void write() {
try(FileWriter fw = new FileWriter("PatientDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(String.format("%-1s %-1s %-1s %-1s %-1s %-1s %-1s",id,name,phno,age,gender,pillness,pregisterdate));
}catch(IOException e){
e.printStackTrace();
}
}
};
Simple solution is using composition create object of doc and patient in appointment class and get doc and patient id from user or create one using objects and write it in third file.
In case of Id you need to search info from file.
In case of new information, as you will be creating object of doctor and patient. first right them in their files and then store data in third file as you want.
If it answer your question let me know.
Create an appointment class and use a search method that accepts the ids to look for (which would look similar to the search methods you already have) then utilize code similar to your write to write to the new file.
I am working on a MabLibs project that is supposed to iterate through a file, prompt you with anything contained in a <> block and allow you to write over to a new file.
I cannot figure out how to use a Scanner to read a file and turn that into a string so I can use the .length() method to iterate a for loop through the file to find these <> blocks.
I can only use Scanner and can't use array lists, so unfortunately the for loop is the only way I can do this.
Here's the code:
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args)
throws FileNotFoundException {
intro();
madLib();
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
System.out.println();
}
public static void madLib() throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String r = input.next();
while (!(r.equalsIgnoreCase("c") || r.equalsIgnoreCase("v")
|| r.equalsIgnoreCase("q"))) {
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
}
if (r.equalsIgnoreCase("v")) {
viewFile();
}
else if (r.equalsIgnoreCase("c")) {
createWord();
}
}
public static void createWord() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
String input2 = input1;
PrintStream output = new PrintStream(new File(toRead));
while (input1.hasNext()) {
String input = input1.next();
for (int i = 0; i < input2.length(); i++) {
if (input.startsWith("<") && input.endsWith(">")) {
String token = input.substring(1, input.length() - 1);
System.out.println("Please input a: " + token);
Scanner scan = new Scanner(System.in);
String replacement = scan.nextLine();
token = token.replace(token, replacement);
output.print(token);
}
}
}
}
public static void viewFile() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
System.out.println();
while (input1.hasNextLine()) {
System.out.println(input1.nextLine());
}
}
}
Any help is greatly appreciated.
I wanted to take a input an array of StringBuffer for user in java but it doesn't work properly:
public class A {
public static void main(String[] args) {
B obj =new B();
Scanner sc= new Scanner(System.in);
int l;
System.out.println("enter the length of string ");
l=sc.nextInt();
StringBuffer sb[]=new StringBuffer[l];
for(int i=0;i<sb.length;i++)
{
System.out.println("enter a string "+(i+1) +" : ");
sb[i]=sb[i].append(sc.nextLine()); // in this line they will give error
}
obj.inputstring( sb);
}
You need to initialize StringBuffer object for each and every sb[i] location.
sb[i]=new StringBuffer(sc.nextLine());
Refer javadoc for Array initialization
Try this.
public static void main(String[] args) {
//B obj =new B();
Scanner sc = new Scanner(System.in);
int l;
System.out.println("enter the length of string ");
l = sc.nextInt();
sc.nextLine();
StringBuffer sb[] = new StringBuffer[l];
System.out.println("sb length==" + sb.length);
for (int i = 0; i < sb.length; i++) {
System.out.println("enter a string " + (i + 1) + " : ");
sb[i] = new StringBuffer(sc.nextLine()); // use StringBuffer(value)
}
for(int j=0;j<sb.length;j++){
System.out.println("string "+j+"="+sb[j]);
}
//for(int j=0;j<=sb.length;j++){}
//System.out.println("sb=="+sb.toString());
}
We have managed to get the code to display the first employee's details, however, the other 2 employee details have it been displayed. I am not sure how to append them. I am not sure if the printWriter is the right thing to out put the code and of not then, what would be best?
The code is below :)
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
try{
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do{
try{
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
}
catch(InputMismatchException ex){
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
}while(repeat==false);
do{
try{
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
}
catch(InputMismatchException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
catch(MissingFormatArgumentException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
}while(repeat);
}finally{
pw.close();
fw.close();
}
}
scan.close();
}
}
So you problem is that each time in for loop you create a new file(deleting the other)
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
put it outside
You don't need fw:
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);// remove this line
...
and also remove this line:
fw.close();
otherwise you'll get NullPointerException
Your problem is that you keep closing pw. Move the close of pw after the for loop. I have modified your code and the following works:
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for (int i = 0; i < 3; i++) {
//FileWriter fw = new FileWriter("Employees.txt", true);
try {
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do {
try {
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
} catch (InputMismatchException ex) {
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
} while (repeat == false);
do {
try {
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
} catch (InputMismatchException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
} catch (MissingFormatArgumentException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
} while (repeat);
} finally {
//pw.close();
//fw.close();
}
}
pw.close();
scan.close();
}
My program is supposed to ask the user for firstname, lastname, and phone number till the users stops. Then when to display it asks for the first name and does a search in the text file to find all info with the same first name and display lastname and phones of the matches.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class WritePhoneList
{
public static void main(String[] args)throws IOException
{
BufferedWriter output = new BufferedWriter(new FileWriter(new File(
"PhoneFile.txt"), true));
String name, lname, age;
int pos,choice;
try
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter First name, last name, and phone number ");
name = input.nextLine();
output.write(name);
output.newLine();
System.out.print("Would you like to add another? yes(1)/no(2)");
choice = input.nextInt();
}while(choice == 1);
output.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
Here is the display code, when i search for a name, it finds a match but displays the last name and phone number of the same name 3 times, I want it to display all of the possible matches with the first name.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class DisplaySelectedNumbers
{
public static void main(String[] args)throws IOException
{
String name;
String strLine;
try
{
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
strLine= br.readLine();
String[] line = strLine.split(" ");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
if(name.equals(part1))
{
// Print the content on the console
System.out.print("\n" + part2 + " " + part3);
}
}
}catch (Exception e)
{//Catch exception if any
System.out.println("Error: " + e.getMessage());
}
}
}
you need to split your line and set your parts inside the while loop:
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
String[] line;
String part1, part2, part3;
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
line = strLine.split(" ");
part1 = line[0];
part2 = line[1];
part3 = line[2];
if(name.equals(part1))
{
System.out.print("\n" + part2 + " " + part3);
}
}