How to display specific data from a file - java

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);
}
}

Related

Read two text files and write specific lines from those two text files into a third file

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.

Reading the String and Int from file, and then looped through?

I'm trying to get it so when it reads through the file, it splits every thing before a comma into an element, and then since there are 10 integer grades, those need to be parsed into an int and then calculated for an average. However, I'm unsure of how to actually accomplish this. I've been looking for a solution for hours and I just can't seem to figure it out. I would really appreciate some help here, as I'm currently running out of brain cells.
Thank you, - from someone new to programming.
The assignment:
https://i.stack.imgur.com/L7E9x.png
The .txt file I'm reading from:
https://i.stack.imgur.com/nxCi4.png
My current code:
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ", ";
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(", ");
String name = splitLine[0];
String scores = splitLine[2];
int i = Integer.parseInt(scores);
}
}
}
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line;
String txtSplitBy = ",";
while ((line = br.readLine()) != null) {
int score = 0;
String grade;
String[] splitLine = line.split(txtSplitBy);
String name = splitLine[0];
for ( int i =1; i <= 10; i++) {
score += Integer.parseInt(splitLine[i]);
}
if ( score < 50 ) {
grade = "B";
}else if ( score < 60 ) {
grade = "A";
}else {
grade = "S";
}
System.out.println(name +"," + (score/10) + "," + grade );
}
You need to add your grade logic here.
Here is my version, I kept it simple, after all, it's your homework!
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ","; // Changed from ', ' to ','
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(",", 2); // The threee caps the number of splits
String name = splitLine[0];
ArrayList<Integer> grades = new ArrayList<>();
String[] rawGrades = splitLine[1].split(","); // List of grades as string
for(String rawGrade : rawGrades) {
grades.add(Integer.parseInt(rawGrade));
}
}
}

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

how to retrive data from a file

how should i retrive file of text1 to be used as a login information..
as i already enter the details in the registration part.. i would like to use the first name and staff id as a username and password for login part..
p/s: im so weak at coding..so please forgive my messy coding :)
here is my code.
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write(text1);
writer.write(text2);
writer.write(text3);
writer.write(text4);
writer.newLine();
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
if (scan.equals(text) && scan.equals(text3)) {
clear();
System.out.println("Access Granted! Welcome!");
} else if (scan.equals(text)) {
System.out.println("Invalid Password!");
} else if (scan.equals(text3)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
It's easy, make it like this :
package com.coder.singleton;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {
}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
StringBuilder sb = new StringBuilder();
String text = "";
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
text = input1.next();
sb.append(text + " ");
System.out.println("Enter your last name:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your NRIC:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your Staff ID:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your position:\n");
text = input1.next();
sb.append(text+ " ");
input1.close();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(sb.toString());
writer.newLine();
writer.close();
System.err.println("Your input data " + sb.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
String savedName = "";
String savedPassword = "";
try {
FileInputStream fis = new FileInputStream(new File("text1.txt"));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String word = "";
String [] arr = null;
while ((word = bufferedReader.readLine())!= null) {
arr = word.split("\\s+");
}
savedName = arr[0];
savedPassword = arr[2];
bufferedReader.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
String userName = input1.next();
System.out.println("Enter Password : ");
String password = input1.next();
if (userName.equals(savedName) && password.equals(savedPassword)) {
clear();
System.out.println("Access Granted! Welcome!");
}else if (userName.equals(savedName) && !password.equals(savedPassword)) {
System.out.println("Invalid Password!");
} else if (!userName.equals(savedName) && password.equals(savedPassword)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
the first,you should insert separator(like newLine) when save the register information to file text1,if not ,you can't distinguish information fields.for example:
fWriter = new FileWriter("d:\\tmp\\pass.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine(); //separator string
writer.write(text1);
writer.newLine();
writer.write(text2);
writer.newLine();
writer.write(text3);
writer.newLine();
writer.write(text4);
writer.newLine();
writer.close();
and then,you should retrieve the register information(just first name and staff) form file text1.txt
BufferedReader reader=new BufferedReader(new FileReader("text1.txt"));
String firstName = reader.readLine();
reader.readLine();
reader.readLine();
String passWord=reader.readLine();
final,compare input information with read information.
if (firstName.equals(text) && passWord.equals(text3)) {
System.out.println("Access Granted! Welcome!");
}
At Registration
You have to insert some delimiter (‘,’, ‘.’, ‘:’, ‘_’, ‘- ‘etc.…) at registration time.
Now Hear I am using “#” delimiter.
After insert that data and Delimiter.
Now At read time You have to split with That Delimiter you can access that data. in array
See Bellow code…
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class TestMyException12
{
static void clear(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write("#");
writer.write(text1);
writer.write("#");
writer.write(text2);
writer.write("#");
writer.write(text3);
writer.write("#");
writer.write(text4);
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else
{
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
String datafile = "";
try
{
FileReader fr = new FileReader("text1.txt");
int i;
while((i = fr.read()) != -1)
{
datafile = datafile+(char)i; // store all data into String obj from File
}
}
catch(Exception e)
{
System.out.println("Error In Login : "+e);
}
String[] userval = datafile.split("#"); // split that data and create part of that data
for(int i = 0 ; i < userval.length ; i++)
{
System.out.println(i+">>>>>"+userval[i]);
}
// userval[] is array that is store all data from that file into part
// after you can put any condition
//System.out.println(text+">>>>>"+userval[0]);
//System.out.println(text3+">>>>>"+userval[3]);
if(text.equals(userval[0]) && text3.equals(userval[3]))
{
clear();
System.out.println("Access Granted! Welcome!");
}
else
{
System.out.println("Please register first!\n");
}
}
}
}

user input name times age

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);
}
}

Categories

Resources