How to add and subtract data from text files in java? - java

I have a value in the text file, say 200. The value is then added or subtracted depending on the user. For instance, if the user wants to subtract 20, the value should update to 180. Then the user adds 10, the value should update to 190. When the user wants to quit, the updated value is saved in the file (190).
This is what I tried:
Double money = inputFile.nextDouble();
System.out.println("What do you want to change the value to?");
double change = keyboard.nextDouble();
delta = money + change;
but it says there is an Exception in thread "main" java.util.InputMismatchException

Please try the below code to get the number from your text file then add/subtract users input with it
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.*;
public class ReadFromFile2
{
public static void main(String[] args)throws Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret words
// like \test as \t (ie. as a escape sequence)
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}

You could take a look at the FileWriter to save the value and the Scanner to be able to read from the file.
With the scanner you're able to read and integer with nextInt().
With the FileWriter you can use the method write(String) with the string being the value.
I don't want to just give you the code for you. Remember that google is your friend and there are alot of tutorials that explain really well and there is also the Java Docs from oracle that can be very useful.

If you use Scanner to read your file, you can use nextInt() to obtain the contents of the file as an int which you can add to or subtract from.

Related

Java hasNextLine() method

I am having a problem with the Scanner class method hasNextLine() (or the hasNext() method). Basically, I am trying to read from a text file that has a list of integer values. I need to read through the text file and store the values that are there in an array (not an arrayList). The code below first goes through the text file to "see" how many values are there. I'm doing this because I can't think of another way to count the total number of integers that are in the text file, and I need to know how long my array has to be.
That being said, once I do that it seems that the hasNextLine() method (or the hasNext() method) "stays" at the bottom of the text file once I loop through:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException
{
int y = 0; //stores numbers from the text file below
int counter = 0; //stores the number of datapoints in the text file to read from
File f = new File("Test Data.txt");// load an external file into a variable of type File.
Scanner reader = new Scanner(f);//instead of using System.in use f.
while (reader.hasNext()) // this will read the file's contents line-by-line
{
y = reader.nextInt();
counter++;/*stores the total number of integers in the Test Data.txt file so I can
know how long my array that stores the numbers from the txt file needs
to be.*/
}//ends loop
System.out.println("YOU HAVE " + counter + " DATA POINTS IN THE FILE");
int [] myNumbers = new int[counter]; //will store the integers from a data file
for (int i = 0; i < counter; i++){
if (reader.hasNext()){
System.out.println(i);
myNumbers[i] = reader.nextInt();
}//ends if statement
}//ends loop filling array
reader.close();
}
}
Is there a way to send the scanner "back to the top" of the text file WITHOUT creating a new scanner object? I know I could just create a new Scanner object, and then just loop and store each data point in an array, but it seems like there should be another way to do what I need to do. Is there? The documentation for the method in question doesn't mention much detail. I tried using the reset() method but that did not work.
I am not using an ArrayList because of a condition of the project I am working on. I understand that I could use an arrayList and not have to worry about counting the number of data values in the text file. However, the student I am helping has not learned about arrayLists yet as his class does not include them in the beginner course he's taking.
When reading the file for the second pass, just dispose the old scanner and get a new one. It is all in one line:
reader = new Scanner(f);
This will overwrite the reader with a reference to a new Scanner, one that reads from the beginning of the file. The old Scanner instance, which is no longer accessible will automatically be cleared by the garbage collector.

Reading integers in a .txt file (Java)

So basically I'm trying to write a program where someone can enter 10 integers, that would then be saved in a .txt file, then opened and averaged together.
I'm doing pretty good so far, I got all the exception handling and saving a file with my inputted integers down, but I'm unsure how to read the file. I'm assuming calculating the average wouldn't be difficult once I have that all done anyways. Here's part of my code with the rest linked below (I really think you'd need to see the full code to better recognize the issue):
public static void closeFile()
{
if (output != null)
output.close();
}
public static void readRecords()
{
try
{
while (input.hasNext())
{
System.out.printf("%s%n", String.valueOf(numbers[i]));
}
}
}
http://pastebin.com/yW6G8N8C
You are not opening the file properly, you need to use a reader for that:
public static void readRecords(){
try (BufferedReader br = new BufferedReader(new FileReader("numbers.txt"))) {
String line;
int[] number = new int[10];
i=-1;
while ((line = br.readLine()) != null) {
i++;
number[i] = Integer.parseInt(line);
System.out.println("number "+i+" = "+number[i]);
}
}
catch(Exception e){
// Handle the trouble
}
}
I am not entirely sure what you want to do with your numbers you get or the exact format of the numbers.txt file but I am assuming you are doing something sensible, like writing one integer per line to your file. Otherwise, adjust the code accordingly to suit your needs.
First of all as mentioned by chalarangelo you are not opening the file correctly. You can use Formatter class to write to file but you can't read from file using that. So you need to use a proper reader like BufferedReader and use its readLine() method.
That aside is it necessary that you store integers together with the string
"Inputted integer: "... If so then its going to be a bit difficult to just get the numbers. I'd advise printing just numbers into the file i.e just do
output.format("%s%n", String.valueOf(numbers[i]));
instead of
output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
After that use a reader and read the line and convert it into integer and store it in the array as mentioned in chalarengo's answer.

How to grab a number from a text file, while ignoring the word in front of it?

So I have a .txt file with only this as the contents:
pizza 4
bowling 2
sleepover 1
What I'm trying to do is, for example in the first line, ignore the "pizza" part but save the 4 as an integer.
Here is the little bit of code I have so far.
public static void addToNumber() {
PrintWriter writer;
Int pizzaVotes, bowlingVotes, sleepOverVotes;
try {
writer = new PrintWriter(new FileWriter("TotalValue.txt"));
}
catch (IOException error) {
return;
}
// something like if (stringFound)
// ignore it, skip to after the space, then put the number
// into a variable of type int
// for the first line the int could be called pizzaVotes
// pizzaVotes++;
// then replace the number 4 in the txt file with pizzaVote's value
// which is now 5.
// writer.print(pizzaVotes); but this just overwrites the whole file.
// All this will also be done for the other two lines, with bowlingVotes
// and sleepoverVotes.
writer.close();
} // end of method
I am a beginner. As you can see my actual, functioning code is very short and I don't know to proceed. If anyone would be so kind as to point me in the right direction, even if you just give me a link to a site, it would be extremely helpful...
EDIT: I stupidly thought PrintWriter could read a file
It's pretty simple actually. All you need is a Scanner, and it's function nextInt()
// The name of the file which we will read from
String filename = "TotalValue.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
int value = 0;
while(in.hasNextLine()){
in.next();
value = in.nextInt();
//Do something with the value here, maybe store it into an ArrayList.
}
I have not tested this code, but it should work, but the value in the while loop is going to be the current value of the current line.
I don't fully understand your question, so comment if you want some clearer advice
Here is a common pattern you'll use in Java:
Scanner sc=new Scanner(new File(.....));
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//....parse tokens
}
// now do something
In your case, it seems like you want to do something like:
Scanner sc=new Scanner(new File(.....));
FrequencyCloud<String> votesPerActivity=new FrequencyCloud<String>()
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//if you know the second token is a number, 1st is a category you can do
String activity=line[0];
int votes=Integer.parseInt(line[1]);
while(votes>0){
votesPerActivity.incremendCloud(activity);//no function in the FrequencyCloud for mass insert, yet
votes--;
}
}
///...do whatever you wanted to do,
//votesPerActivity.getCount(activity) gets the # of votes for the activity
/// for(String activity:votesPerActivity.keySet()) may be a useful line too
FrequencyCloud: http://jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java
String num = input.replaceAll("[^0-9]", " ").trim();
For sake of diversity this uses regular expressions.

How do I do computations on a user inputed list of numbers in JAVA?

I need to know how to do computations on a user inputed list of numbers. Here's my code so far, I'm lost as to how to proceed. I need to write a code that asks whether or not the user wants to manually input numbers or upload from a file. If user chooses manual, I have to find the average, min, max, and stand. dev. of the numbers they input. Any help would be appreciated
import java.io.*;
public class computation {
//main method starts
public static void main (String[] args) throws Exception {
//create text input reader
InputStreamReader get = new InputStreamReader(System.in);
BufferedReader got = new BufferedReader(get);
//create a text printer
PrintWriter send = new PrintWriter(System.out,true);
//defining a string type variable for user input
String answer1;
//asks the user if they want to input data from keyboard
String question = "Do you want to input data manually? Enter y or n";
send.println(question);
//system reads user input
answer1 = got.readLine();
if (answer1.equals("y")) {
send.println("Enter numbers separated by spaces");
String datacurrent = got.readLine();
} //end of "y" if
if (answer1.equals("n")) {
send.println("Enter the path of your data file");
} //end of "n" if
} //end of main method
} //end of class computation
I just ran your program, it seems alright.
(A) What to do when values inputted through console ?
Split the string into an array, extract each number and then calculate Average, Min, Max, and Stand deviation.
For ex:
String[] numbers = datacurrent.split(",");
for(int i=0; i<number.length; i++)
{
....
}
(B) What to do when inputted as file path ?
You will have to read the file using File Stream/Buffer Reader.
BufferedReader reader = new BufferedReader(new FileReader(Your string variable pointing to path));
And then loop through file data.
Note: You need to know the text file format in order to loop through the file content.
You might want to look at the newer class System.console that we got that faciliates easier console i/o. Your program shows attempt and if you study one or two good Java books you will beable to write this program error-free. Two good new Java books are the Sierra / Bates OCJP study guide and the new A Press Java 7 book. I recommend you take a read or two from one or two of these books and you will learn how to use ? System.console for console i/o.
System.out.print("Enter something:");
String input = System.console().readLine();

java.util.Scanner: keeps waiting for additional input

Total Java newbie here. Working on one of my very first Java programs. Please help.
Here's what I am trying to achieve:
I need to accept user keyboard input of whitespace separated integers, copy them into an array and process them. KNOWN: user will enter only ONE line of data. I don't know how many numbers, but once they hit Enter, there won't be any more. As user input may contain words and special characters, I need to handle them with neat errors and prompt user to try again. When I run what I wrote below, I get in some kind of infinite loop where Scanner keeps waiting for additional input. How do I tell it it's over and there won't be any more input?
Here's the code:
<!-- language-all: java -->
public static void EnterInts () {
System.out.println("Enter series of integers separated by whitespace. Press Enter key when finished.");
Scanner input = new Scanner(System.in);
while (input.hasNext()){
if (input.hasNextInt(){
int i = input.nextInt();
System.out.println(i);
}
else {
System.out.println("Only integers can be entered. Try again.");
}
}
}
Seems like you should read the single line of input first, then create the Scanner to scan through that single line.
Try using a BufferedReader and InputStreamReader to read the line first:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = in.readLine();
And then create the Scanner, perhaps passing a StringBufferInputStream created from the read string into its constructor.

Categories

Resources