Saving Inputs to txt. file in Java - java

I have been building program, where a. teacher is asked for information of 5. students and all the inputs should be saved after to a txt. file. Although my file is always created but is always empty...
Could someone please help me find my mistake ?
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class programming_project_1 {
public static void main(String[] args) throws IOException
{
int numbersOfLoops = 1;
Scanner scn = new Scanner(System.in);
while (true){
if (numbersOfLoops == 6){
break;
}
System.out.println("First Name: " );
String first_name = scn.next();
System.out.println("Last Name: " );
String last_name = scn.next();
System.out.println("Final Score: ");
int score = scn.nextInt();
numbersOfLoops++ ;
PrintWriter out = new PrintWriter("grades.txt");
System.out.println("First Name: " + first_name);
System.out.println("Last Name: " + last_name);
System.out.println("Final Score: " + score);
out.close();
}
}
}

You never write to out. Here:
System.out.println("First Name: " + first_name);
System.out.println("Last Name: " + last_name);
System.out.println("Final Score: " + score);
you probably meant out.println instead of System.out.println.
System.out is a PrintStream that writes to standard output. out, on the other hand, is a PrintWriter you declared and that writes to a file.
Also, you probably want to open the file before the loop and only close it afterwards, otherwise each iteration will overwrite the previous one.
Finally, a couple of asides:
that's a weird way of looping 5 times. You could use a for instead.
You should strive to respect java naming convention. Class names Start with an upper-case letter and use CamelCase, not snake_case. Same for variables, but they start with lower-case letters.
To sum it up:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class ProgrammingProject1 {
public static void main(String[] args) throws IOException
{
Scanner scn = new Scanner(System.in);
PrintWriter out = new PrintWriter("grades.txt");
for (int i = 0; i < 5; i++) {
System.out.println("First Name: " );
String firstName = scn.next();
System.out.println("Last Name: " );
String lastName = scn.next();
System.out.println("Final Score: ");
int score = scn.nextInt();
out.println("First Name: " + firstName);
out.println("Last Name: " + lastName);
out.println("Final Score: " + score);
}
out.close();
}
}

Related

How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation

Initials of a name

I want to show my initials in a code. For example, if my name is Donald Trump, the program shall write D.T.
How do I do this the easiest way?
package pack_prov;
import javax.swing.*;
public class Filip_Degeryd_uppgift_3 {
public static void main(String[] args) {
String f;
String e;
f = JOptionPane.showInputDialog("first name ");
e = JOptionPane.showInputDialog("last name ");
JOptionPane.showMessageDialog(null, "initials " + f + e + "is" +
f.charAt(0) + ".") + e.charAt(0);
}
}
Here:
public class Test {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter First Name:");
String frstNme = scn.nextLine();
System.out.println("Enter Last Name:");
String lstNme = scn.nextLine();
System.out.println("Your Name Initial Is: " + frstNme.substring(0, 1) + "." + lstNme.substring(0, 1) + ".");
scn.close();
}
}

TreeMap collection issue

I am trying to create a program to keep track of College Teams and their sports records(Wins, Losses, years played). I want to use a Map(I opted for TreeMap) and a Set(I opted for TreeSet). I want to read the teams from a file and based on the input, update the database. For instance the line: 1975:UCLA:Brown would increment a win for UCLA, increment a loss of Brown and add the year 1975 to both teams.
The Key for the tree map will be the college names. the values is an object called TeamInfo
import java.util.TreeSet;
class TeamInfo {
int wins = 0;
int losses = 0;
TreeSet years;
TeamInfo(int wins, int losses, String year) {
// provide constructor code here
this.wins = wins;
this.losses = losses;
years = new TreeSet();
}
void incrementWins() {
wins++;
}
void incrementLosses() {
losses++;
}
void addYear(String aYear) {
// provide addYear code here
years.add(aYear);
}
public String toString() {
// provide toString() code here
return " Wins: " + wins + " Losses: " + losses + "\n" + "Years: " +
years.toString();
}
} // end TeamInfo
Ideally after reading from a file I should get the output:
Name: UCLA Wins:1 Losses:0
Name: Brown Wins:0 Losses: 1
My Problem comes when I have input like this:
1939:Villanova:Brown
1940:Brown:Villanova
1940:Brown:Villanova
I get output like this:
Name: Brown Wins: 2 Losses: 0
Years: [1940]
Name: Brown Wins: 0 Losses: 1
Years: [1939]
Name: Villanova Wins: 1 Losses: 1
Years: [1939, 1940]
Name: Villanova Wins: 0 Losses: 1
Years: [1940]
When the output should resemble:
Name:Brown Wins:2 Losses: 1
Name: Villanova Wins:1 Losses: 2
There are separate records for wins and losses for each team, when there should only be one record with both wins and losses. I've been staring at my code for hours and can't seem to see why it is doing that. Can anyone tell me what error I am committing and why this could be happening?
Thank You!
Here is my Main Class:
import java.util.TreeMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
public class Records {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
File input = new File("C:\\Users\\Christian\\Desktop\\C code\\input4.txt");
Scanner test = new Scanner(input).useDelimiter("[:\n]");
TeamInfo tester;
String year ="";
String winner="";
String loser="";
TreeMap records = new TreeMap();
TeamInfo temp = new TeamInfo(0,0,"");
while(test.hasNext())
{
year = test.next();
winner = test.next();
loser = test.next();
/*search(test.next)
increment win
*/
if(!records.containsKey(winner))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementWins();
firstRecord.addYear(year);
records.put(winner, firstRecord);
// System.out.println("First iteration of " + winner);
}
else if(records.containsKey(winner))
{
temp = (TeamInfo)records.get(winner);
temp.incrementWins();
temp.addYear(year);
records.replace(winner, temp);
// System.out.println("FOUND " + winner);
}
/*
search(test.next)*/
if(!records.containsKey(loser))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementLosses();
firstRecord.addYear(year);
records.put(loser, firstRecord);
// System.out.println("First iteration of " + loser);
}
else if(records.containsKey(loser))
{
temp = (TeamInfo)records.get(loser);
temp.incrementLosses();
temp.addYear(year);
records.replace(loser, temp);
// System.out.println("FOUND " + loser);
}
/*increment loss
*/
}
while(!records.isEmpty())
{
temp = (TeamInfo)records.get(records.firstKey());
System.out.println("Name: " + records.firstKey().toString() + temp.toString());
records.remove(records.firstKey());
}
}
}

using Bufferdwriter why am I receiving main class not found or can't load?

I create a program that accepts user input. Based on the sales amount I am requesting the data go to either a low sales txt file or a high sales txt file. When I run the program I receive error Error: Could not find or load main class HighandLowSales. How can it not find or load the main class?
My previous post regarding the if else statement in case you would like to see: How to specify which file to write to?
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class HighandLowSales
{
public static void main(String[] args)
{
Scanner input1 = new Scanner(System.in);
Path highPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 "
+ "Programming Logic\\Week7\\HighSales.txt");
Path lowPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 Programming Logic\\"
+ "Week7\\LowSales.txt");
String delimiter = ",";
String s;
int id;
String firstName;
String lastName;
double currentSales;
final int QUIT = 999;
try
{
Scanner input = new Scanner(System.in);
OutputStream output = new
BufferedOutputStream(Files.newOutputStream(highPerformer, CREATE));
OutputStream output1 = new
BufferedOutputStream(Files.newOutputStream(lowPerformer, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(output));
BufferedWriter writer1 = new
BufferedWriter(new OutputStreamWriter(output1));
System.out.print("Enter employee ID number >> ");
id = input.nextInt();
while(id != QUIT)
{
System.out.print("Enter first name for employee #" +
id + " >> ");
input.nextLine();
firstName = input.nextLine();
System.out.print("Enter last name for employee # " +
id + " >> ");
input.nextLine();
lastName = input.nextLine();
System.out.print("Enter current month sales in whole dollar "
+ "for employee #" + id + " >> ");
input.nextLine();
currentSales = input.nextDouble();
s = id + delimiter + firstName + delimiter + lastName + delimiter
+ currentSales;
if (currentSales>1000)
{
writer.write(s);
}
else
{
writer1.write(s);
}
writer.newLine();
writer1.newLine();
System.out.print("Enter next ID number or " + QUIT
+ "to quit");
id = input.nextInt();
}
writer.close();
writer1.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
The file HighandLowSales.java must be exactly in the same case, not for instance HighAndLowSales.java. Either that or you are not executing the application with the correct class path: java -cp . HighandLowSales. But as it seems you just clicked the jar, I guess it is the case-sensitive nature of java file names (in jars, under Linux, MacOSX).
(Also it is really customary to no longer use the default (=no) package.)

Loop is not working

this code is to be used to write the data inserted in to a file
when the loop runs the second student dont get entered i dont know why
this keeps getting stuck at the second student and i have been working on this for hours
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.nextLine();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
ww.close();
counter++;
stnum++;
}
}
}
You close your FileWriter in each iteration of your while loop... what did you think would happen?
you close the writer in the loop, move the close statement outside of the loop
ww.close();
Things to do
put ww.close(); outside the while loop
change c.nextLine(); to c.next();
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.next();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
counter++;
stnum++;
}
ww.close();
}
}

Categories

Resources