creates the file doesnt write java [duplicate] - java

This question already has answers here:
How to read from user's input in Java and write it to a file
(2 answers)
Closed 7 years ago.
public static void main(String[] args) throws FileNotFoundException {
#SuppressWarnings("unused")
Scanner in = new Scanner(System.in);
System.out.println("enter filename");
Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
outputFile.close();
getInput();
display();
}
public static void display() throws FileNotFoundException{
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i]+";"+genders[i]+";"+emails[i]+";"+salaries[i]);
}}
public static void getInput(){
System.out.print("How many users do you wish to enter: ");
int num = in.nextInt();
ages= new int[num];
genders = new String[num];
emails = new String[num];
salaries = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("Please enter your age for person "+(i+1)+": ");
ages[i] = in.nextInt();
while (ages[i]<20 ||ages[i]>30){
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();}
in.nextLine();
hey guys i am trying to write the contents of user input into a file. my problem is it creates the file but doesnt write to it. i have tried various methods but doesnt work any help?

Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
I think you are creating the file with the name of user input, and prints an empty line to it

Your question is answered here: https://stackoverflow.com/questions/18070629/how-to-read-from-users-input-in-jav‌​a-and-write-it-to-a-file
But to summarise: You are simply creating a file named after the user's input. You need to actually write that information to the file:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
private static String fileName;
private static String[] genders, emails;
private static double salaries[];
private static int userCount;
private static int[] ages;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
System.out.println("enter filename");
fileName = in.nextLine();
File myFile = new File(fileName);
getInput();
display();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(myFile);
writer = new BufferedWriter(fWriter);
writer.write(display().toString());
writer.newLine();
writer.close();
} catch (Exception e) {
System.out.println("Error!");
}
}
public static ArrayList<String> display() throws FileNotFoundException {
ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < genders.length; i++) {
data.add(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
return data;
}
private static void getInput() {
System.out.print("How many users do you wish to enter: ");
int userCount = in.nextInt();
ages = new int[userCount];
genders = new String[userCount];
emails = new String[userCount];
salaries = new double[userCount];
for (int i = 0; i < userCount; i++) {
System.out.print("Please enter your age for person " + (i + 1) +
": ");
ages[i] = in.nextInt();
while (ages[i] < 20 || ages[i] > 30) {
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();
}
in.nextLine();
}
}
}

Related

getting this error -> Exception in thread "main" java.util.InputMismatchException in Java

I'm getting the error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.raghuvamsha.Main.main(Main.java:24)
in my program:
1. Main Class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
int a = 0;
while(a!=6) {
Scanner reader = new Scanner(System.in);
a = reader.nextInt();
System.out.println("You entered integer " + a);
if(a==1){
AddNewMember anm = new AddNewMember();
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
}
AddNewMember Class.
public class AddNewMember {
private FileWriter x;
private Formatter form;
public void openFile(){
try{
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
}
catch (Exception e){
System.out.println("You have an error");
}
}
public void addRecords(){
//Adding Animal Name.
System.out.println("Please input animal name: ");
Scanner reader_an = new Scanner(System.in);
String animal_name = reader_an.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
Scanner reader_aofn = new Scanner(System.in);
String animal_ofn = reader_aofn.next();
System.out.println("Last Name: ");
Scanner reader_aoln = new Scanner(System.in);
String animal_oln = reader_aoln.next();
//Adding species.
System.out.println("Please input animal species: ");
Scanner reader_s = new Scanner(System.in);
String animal_s = reader_s.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
Scanner reader_dob = new Scanner(System.in);
String animal_dob = reader_dob.next();
//Adding Treatments
List<String> animal_treatments = new ArrayList<String>();
System.out.println("Please input treatments: ");
int i = 0;
Scanner reader_treatments = new Scanner(System.in);
while (i<10) {
String s = reader_treatments.next();
if (s.equals("q")|| s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
}
public void closeFile(){
form.close();
}
}
I have read some posts in StackOverflow regarding the issue, it was mentioned to use next() instead of nextLine() in my code, but still it was not working. Please help me.
Thank you.
The Upshot
First, you shouldn't be creating multiple instances of Scanner. But your main problem is that you aren't doing error checking on the input that the user is giving you. The InputMismatchException was probably thrown beacause you entered something other than an integer on the menu. Try this code to fix it:
Main.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
int a = 0;
Scanner reader = new Scanner(System.in);
while (a != 6) {
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
boolean intValid = false;
while(!intValid) {
System.out.println("Please enter a valid option (1 - 6).");
String input = reader.next();
if (isInteger(input)) {
a = Integer.parseInt(input);
if (a >= 1 && a <= 6) {
intValid = true;
}
}
}
System.out.println("You entered integer " + a);
if (a == 1) {
AddNewMember anm = new AddNewMember(reader);
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
private static boolean isInteger(String str) {
return str.matches("-?\\d+");
}
}
AddNewMember.java
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
import java.util.List;
public class AddNewMember {
private FileWriter x;
private Formatter form;
private Scanner reader;
public AddNewMember(Scanner reader) {
this.reader = reader;
}
public void openFile() {
try {
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
//Adding Animal Name.
System.out.println("Please input animal name: ");
String animal_name = reader.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
String animal_ofn = reader.next();
System.out.println("Last Name: ");
String animal_oln = reader.next();
//Adding species.
System.out.println("Please input animal species: ");
String animal_s = reader.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
String animal_dob = reader.next();
//Adding Treatments
List <String> animal_treatments = new ArrayList <String>();
System.out.println("Please input treatments: ");
int i = 0;
while (i < 10) {
String s = reader.next();
if (s.equals("q") || s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
reader.close();
}
public void closeFile() {
form.close();
}
}
A Side Note
I don't know if this is for a school project of something you are making on your own, but if you really want to handle user input with a nice interface, take a look at Java Swing.
Also, you will have to do a lot more error checking on the input fields for the input in AddNewMember if you don't want similar errors in the future.
Happy Coding!

Not able to get full 100 test case in Google code jam.My Output case Generate only two case instead of 100

INPUT FILE LINK
I am trying to solve Google Apac past Questions ,i have read an input from the file the no.of test cases are 100,but it only generate 2 output cases,Can any one help?
Trying to solve from last week but does'nt able to get required output file.
The code is posted below,Any help will be highly appreciated
Thank you
import java.io.*;
import java.util.*;
class Jam
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(new
FileReader("C:/Users/AAKASH/eclipse/Downloads/A-small-practice-1.in"));
PrintWriter pw = new PrintWriter(new
FileWriter("C:/Users/AAKASH/eclipse/Downloads/A-small-practice-1.out"));
HashSet<String>hset=new HashSet<String>();
int T=sc.nextInt();
sc.nextLine();
for(int i=1;i<=T;i++)
{
int M=sc.nextInt();
sc.nextLine();
if(M>=1&&M<=10)
{
int d=2*M;
String Name[]=new String[d];
for(int j=0;j<d;j++)
{
Name[j]=sc.next();
hset.add(Name[j]);
}
if(hset.size()<Name.length)
{
pw.println("Case #"+i+":"+" "+"NO");
}
if(hset.size()==Name.length)
{
pw.println("Case #"+i+":"+" "+"YES");
}
}
}
pw.flush();
pw.close();
sc.close();
}
}
I have made some changes to your main method, now it is generating result for all test cases but you need to verify the logic and output.
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(new FileReader("D:/A-small-practice-1.in"));
PrintWriter pw = new PrintWriter(new FileWriter("D:/A-small-practice-1.out"));
HashSet<String> hset = new HashSet<String>();
int T = Integer.parseInt(sc.nextLine().trim());
for (int i = 1; i <= T; i++) {
String str = sc.nextLine().trim();
int M = Integer.parseInt(str);
if (M >= 1 && M <= 10) {
int d = 2 * M;
String Name[] = new String[d];
for (int j = 0; j < d; j++) {
Name[j] = sc.next();
hset.add(Name[j]);
}
if (hset.size() == Name.length) {
pw.println("Case #" + i + ":" + " " + "YES");
} else {
pw.println("Case #" + i + ":" + " " + "NO");
}
}
sc.nextLine();
}
pw.flush();
pw.close();
sc.close();
}

What if I want to make this class as a list in java?

I've just made this simple student program which reads the data and writes into the file.
What I need is if I want to enter 100 data of students how to make it in a list and that should be from user side
For example,
Enter students you want to enter : 2
Name : Satish devnani
Roll No : 1
Name : Sonu
Roll No : 2
And if user enters 100 then it should be 100.
made until this :
import java.util.*;
import java.io.*;
class filesatish2{
String name;
int number;
//int i=0;
public static void main(String args[]) throws IOException {
//int i;
filesatish2 stname= new filesatish2();
Students.READ();
Students.FILEWRITE();
}
int HOWMANY()
{
int count;
Scanner sc=new Scanner(System.in);
printit("How many data you want to enter ?");
count=sc.nextInt();
//printit(""+count);
return count;
}
void READ()
{
Scanner sc=new Scanner(System.in);
Scanner text=new Scanner(System.in);
printit("Name :");
name=text.nextLine();
printit("Number :");
number=sc.nextInt();
}
public static void printit(String a)
{
System.out.print(a);
}
public void FILEWRITE() throws IOException
{
File student = new File("Student.txt");
FileWriter printer = new FileWriter(student);
student.createNewFile();
printer.write(""+name);
printer.write("\t"+number);
printer.flush();
printer.close();
}
}
try the following:
import java.util.*;
import java.io.*;
class filesatish2 {
List studentList = new ArrayList();
String name;
int number;
int count = 0;
public static void main(String args[]) throws IOException {
// int i;
filesatish2 stname = new filesatish2();
stname.count = stname.HOWMANY();
stname.READ();
stname.FILEWRITE();
}
int HOWMANY() {
int count;
Scanner sc = new Scanner(System.in);
printit("How many data you want to enter ?");
count = sc.nextInt();
// printit(""+count);
return count;
}
void READ() {
Scanner sc = new Scanner(System.in);
Scanner text = new Scanner(System.in);
for (int i = 0; i < count; i++) {
printit("Name :");
name = text.nextLine();
printit("Number :");
number = sc.nextInt();
studentList.add(name + "\t" + number + "\n");
}
}
public static void printit(String a) {
System.out.print(a);
}
public void FILEWRITE() throws IOException {
File student = new File("Student.txt");
FileWriter printer = new FileWriter(student);
student.createNewFile();
for (int i = 0; i < count; i++) {
printer.write((String) studentList.get(i));
}
printer.flush();
printer.close();
}
}

How can I read and compare numbers from a text file?

I've a text file and eclipse reads that without problem. The problem is that I don't know how I can hold the numbers from the FileReader. My program is supposed to read a text from a file that file has 2 names with their school points.
For example:
Jack 30 30 30
Martin 20 20 30
How can I find the one with the greater points?
public static void main(String[] args) {
String name = null;
try {
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.nextLine();
System.out.println(name);
///?? what do i have to write to compare to persons points
}
} catch(IOException e) {
System.out.println("The file does not exist");
}
}
I know, it is not an efficient method, but I solved the problem with this code:
public static void main(String[] args)
{
String name = null;
int i = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
try
{
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.next();
System.out.println(name + " ");
while (file.hasNextInt())
{
i = i + file.nextInt();
}
if (i < min)
{
min = i;
}
System.out.println("min " + min);
if (i > max)
{
max = i;
}
System.out.println("max " + max);
i = 0;
}
} catch (IOException e)
{
System.out.println("File does not exist");
}
}
This probably isn't the most efficient way of solving it, but I gave it a shot. It isn't the full code for comparing multiple lines but you can just run this through a while loop until the file doesn't have next like you were already doing. Once you run this through you can store the value of each line to a variable and then compare the variables. ex: boolean xIsBigger x > y;. Then if it is true, x is the bigger number but if it is false then you know y is the bigger number. Hope this helps.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
String line = "Jack 20 20 20";
line = line.replaceAll("[^0-9]", " ");
line = line.replaceFirst("^ *", "");
line = line.replaceAll(" ", "+");
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(line));
}
}
System output: 60.

IOException Loop

I need help figuring out how to loop my IOException (in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.
import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}
Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}

Categories