Reading numbers from a .txt file in java and adding them - java

I have a text file with some account holders and numbers of books they have on loan. I need to read the file, add how many account there are and add the total number of books.
These are the account holders and the total number of books.
Tim Newton 14
Leon Jones 21
Bill Bob 94
Sarah Gooding 67
{
private int count;
private File inFile, outFile;
private Scanner input;
private String name;
private PrintWriter output;
private int total;
public test(String name, String id, String inFileName, String outFileName) {
inFile = new File(inFileName);
if (!inFile.exists()) {
throw new IllegalStateException(inFileName + " does not exist");
}
outFile = new File(outFileName);
}
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
}
public void processFiles() {
try {
while (input.hasNext()) {
String line = input.nextLine();
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
public void closeLink() {
try {
input.close();
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
try {
output.close();
} catch (NullPointerException e) {
System.out.println(" PrintWriter not assigned");
}
}
}
Here is the edited code with the scanner answer implemented:
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
numbers = new Scanner(inFile)
}
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
String line = input.nextLine()
while (numbers.hasNextInt()) {
total += numbers.nextInt();
}
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
enter code here

Use scanner.hasNextInt() and scanner.nextInt()
You may want to have another scanner that looks for numbers in the file:
private Scanner account; // initialise this in makeLink
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
total += account.nextInt();
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
Note: It is worthwhile to read the java API.

Related

Creating an Object in a Class then using it in different class

I'm trying to create an object in one class then use that object in another class but each time I try to use it it just says the value is null
Customer cus = new Customer();
ServerSocket s = null;
public AddCustomer() {
}
public void getCustomerDetail() {
String back = " ";
{
try {
s = new ServerSocket(5433);
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
System.exit(0);
}
while (back.equals(" ")) {
try {
Socket s1 = s.accept();
System.out.println("Connection established at port 5433");
InputStream is = s1.getInputStream();
ObjectInputStream dis = new ObjectInputStream(is);
System.out.println("Getting data...");
cus = (Customer)dis.readObject();
System.out.println(cus.toString());
System.out.println(cus.getName());
dis.close();
s1.close();
System.out.println("Connection closed.");
} catch (ConnectException connExcep) {
System.out.println("1Error: " + connExcep.getMessage());
} catch (IOException ioExcep) {
System.out.println("2Error: " + ioExcep.getMessage());
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
}
}
}
public void addCustomerToDB() {
System.out.println("start ");
Connection connection = null;
Statement statement = null;
int check = 1;
System.out.println(cus.getName()+"dadawd");
}
When I print out the value of cus.getName() it just gives me null but when I print it out in getCustomerDetail it gives me the correct value.
dis.readObject returns an object with the values in it.
Depends on what you are doing in the getName function and in the constructor.
Maybe in getCustomerDetails() you are setting the values in the input stream. But the default constructor doesn't do anything with name variable.
It looks like the issue of packaging. Try below code.
public class AddCustomer {
public static void main(String[] args) {
new AddCustomer().getCustomerDetail();
}
Customer cus = new Customer();
public void getCustomerDetail() {
String back = " ";
{
while (back.equals(" ")) {
try {
System.out.println(cus.toString());
System.out.println(cus.getName());
System.out.println("Connection closed.");
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
break;
}
}
}
public void addCustomerToDB() {
System.out.println(cus.getName()+"dadawd");
}
}
class Customer{
private String name="ABC";
String getName() {
return name;
}
}
We found here one issue you have to create "Customer cus = new Customer();" this object under main() function like as
public class AddCustomer {
public static void main(String[] args) {
Customer cus = new Customer();
new AddCustomer().getCustomerDetail();
}

Why can't I add text to a file in Java? [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 3 years ago.
It seems that its creating a new file always I try to write or read.
Each line starts with the name of the player, if exists the player should add the score at the end, if not creates a new line and write the info.
.......................
public class JogadorData {
private String nome_player;
private Scanner is;
private FileWriter os;
// this file exists
private final String path = "src/Data/JogadorData";
public JogadorData(String nome_player) {
this.nome_player = nome_player;
try {
is = new Scanner(new File(path));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
os = new FileWriter(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public void escreverScore(String score) {
if (jogadorNovo(nome_player)) {
try {
os.write(nome_player + " " + score);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
escreverResultadoJogadorExistente(score);
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns true if it is a new player
private boolean jogadorNovo(String nome_player) {
while (is.hasNextLine()) {
String linha = is.nextLine();
String[] info = linha.split(" ");
if (info[0].equals(nome_player)) {
return false;
}
}
return true;
}
}
....................................
....................................
Test:
public class TESTE {
public static void main(String[] args) {
JogadorData jogador = new JogadorData("Manelina");
jogador.escreverScore("100");
// System.out.println(jogador.lerMelhorResultado());
}
}
The example below is a simplified read/write to file from what you have, done in similar format to what you are trying to do. What this code does is reads every line from the file you are loading from via Files#readAllLines, then runs through each line, (put your logic where I commented the if statement, and then output.add appends the new version of the line you are modifying, storing it in the array list "output", after which the file is saved to the path defined by Files#write
List<String> output = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("Path/To/File.txt"));
for (String line : lines) {
//... if (playerExists(line))
output.add(line + " " + score);
}
Files.write(Paths.get("Path/To/Save/File.txt"), output);

Scanner to byte[]?

I have to copy txt file to RAM(use ByteArrayOutputStream), next to make a list with all of the words and number of repeats.
But when I try print that list, it print me
"java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=false][need input=false][source
closed=false][skipped=false][group separator=\ ][decimal
separator=\,][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
I found here where is the problem(That Scanner is not a String Object)but can't find a solution.
Could u check my code and help?
{
public class JavaRam {
File f;
byte [] bTab;
Scanner sc;
String tempLine;
ByteArrayOutputStream baos;
StringTokenizer st;
long startTime=0;
long stopTime=0;
HashMap<String,Integer> hm;
JavaRam(String fileName) throws IOException{
startTime=System.currentTimeMillis();
loadFile(fileName); //load file to ram
System.out.println("Czas ladowania pliku: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
hm=new HashMap<String, Integer>();
makeList();
System.out.println("Czas tworzenia listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
printing();
System.out.println("Czas drukowania listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
exit();
System.exit(0);
}
void loadFile(String fileName){
try{
f=new File(fileName+".txt");
sc=new Scanner(f);
}
catch(Exception e){
e.printStackTrace();
}
tempLine=new String(sc.toString());
bTab=tempLine.getBytes();
baos=new ByteArrayOutputStream();
try{
baos.write(bTab);
}
catch(Exception e){
e.printStackTrace();
}
}
void makeList(){
st=new StringTokenizer(baos.toString());
Integer ti; //temporary int
for(String nt=st.nextToken(); st.hasMoreTokens()==true;nt=st.nextToken()){
if(hm.containsKey(nt)==false){
hm.put(nt, 1);
}
else{
hm.put(nt,(Integer)hm.get(nt)+1);
}
}
}
void printing(){
String sl="Slowo";
String lp="Liczba powtorzen:";
String sl1="";
String lp1="";
for(String str:hm.keySet()){
sl1=sl+str;
lp1=lp+hm.get(str).toString();
System.out.printf("\n %-20s, %-20s",sl1,lp1);
}
}
int exit() throws IOException{
baos.close();
sc.close();
return 1;
}
public static void main(String []args){
try {
JavaRam a=new JavaRam("JPJMMWKM");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Thanks in advance ;)
tempLine=new String(sc.toString()); that seems wrong; you probably wants sc.nextLine().
Anyway, your code is really confusing. The code in the constructor should be go into another method, too much instance members, etc, etc.

Why am I getting a false value at if (users.contains(user))?

I think the user.contains is not reading every line and is only checking the first line. I had this working right earlier(I am testing the duplicate user portion of my code), but now my program is skipping :
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
I am not sure what I did, or how I managed to break my own program. Now its skipping all the way to:
else { if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
}
Where did I go wrong?
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
String un = UserName.getText().trim();
String pw = Password.getText().trim();
HashSet hs= new HashSet();
HashSet users = new HashSet();
boolean goahead=true;
try {
Scanner Scan = new Scanner(new File("Login.txt"));
while (Scan.hasNextLine()) {
String authenticator = Scan.nextLine().trim();
String[] autparts=authenticator.split(" ");
String user = autparts[0].trim();
if (goahead){
if (users.contains(user)) {
if (user.equals(un)) {
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
} else {
hs.add(authenticator);
users.add(user);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (goahead) {
if (createAccount.isSelected() & (hs.contains(new String(un+" "+pw)))){
JOptionPane.showMessageDialog(null,"User Already Exsist! No Need to create a new account. ");
dispose();
} else {
if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
} else {
if (createAccount.isSelected()){
try {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Login.txt", true)));
output.println(un+" "+pw);
output.close();
} catch (IOException ex) {
System.out.printf("error %s/n", ex );
}
JOptionPane.showMessageDialog(null,"Welcome!"+" " + un+" "+"Please Relogin Now");
dispose();
}else {
JOptionPane.showMessageDialog(null, "user doesn't exist or password incorrect. ");
dispose();
}
}
}
}
the following is my output and whats in the txt file. :
I have formatted your code now:
String un = UserName.getText().trim();
if (goahead){
if (users.contains(user))
{
if (user.equals(un))
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
}
else
{
hs.add(authenticator);
users.add(user);
}
}
Now when the flag goahead is set to false dont we need to reset it to true somewhere? If HashSet contains user then why do you need to again compare name of user? You should have defined equals for the user itself. Nope?
You seem to chasing your tail, doing two things at one, reading the file/populating the Set AND checking for duplicates. Instead, do one at a time...
Something like...
// You could pre-load these and cache the result instead
// of reading it each time, but that's up to you
Map<String, String> credentials = new HashMap<>(25);
try (Scanner scan = new Scanner(new File("Login.txt"))) {
while (scan.hasNextLine()) {
String value = scan.nextLine();
String[] parts = value.split(" ");
credentials.put(parts[0], parts[1]);
}
} catch (IOException exp) {
exp.printStackTrace();
}
// Make your required checks here
if (credentials.containsKey(un)) {
if (credentials.get(un).equals(pw)) {
// Validated
} else {
// Wrong password
}
} else {
// New user...?
}

binary search from a file

how can I search a data using binary search? When if statement begins, the program goes to IOException block. It seems that it doesn't try to read the file.
public void busquedaDicotomica1(String clave)
{
String lectura1=null, lectura2=null ;
long posicion;
long tamaño;
long midValue;
boolean valido = true;
try
{
rafObj = new RandomAccessFile("indice1.ind","r");
tamaño = rafObj.length();
midValue = tamaño/2;
rafObj.seek(midValue);
if(clave.equalsIgnoreCase(rafObj.readUTF()))
{
System.out.println("ok");
}
else
{
System.out.println("no");
}
}
catch(EOFException eoe)
{}
catch(FileNotFoundException nfe)
{
VentanaPrincipal.setErrorText(dialogo);
}
catch(IOException ioe)
{
VentanaPrincipal.setErrorText(ioe.getMessage());
}
}
}

Categories