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.
Related
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.
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks
Below is how i count the number of lines in a text file. Just wondering is there any other methods of doing this?
while(inputFile.hasNext()) {
a++;
inputFile.nextLine();
}
inputFile.close();
I'm trying to input data into an array, i don't want to read the text file twice.
any help/suggestions is appreciated.
thanks
If you are using java 7 or higher version you can directly read all the lines to a List using readAllLines method. That would be easy
readAllLines
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
Then the size of the list will return you number of lines in the file
int noOfLines = lines.size();
If you are using Java 8 you can use streams :
long count = Files.lines(Paths.get(filename)).count();
This will have good performances and is really expressive.
The downside (compared to Thusitha Thilina Dayaratn answer) is that you only have the line count.
If you also want to have the lines in a List, you can do (still using Java 8 streams) :
// First, read the lines
List<String> lines = Files.lines(Paths.get(filename)).collect(Collectors.toList());
// Then get the line count
long count = lines.size();
If you just want to add the data to an array, then I append the new values to an array. If the amount of data you are reading isn't large and you don't need to do it often that should be fine. I use something like this, as given in this answer: Reading a plain text file in Java
BufferedReader fileReader = new BufferedReader(new FileReader("path/to/file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you are reading in numbers, the strings can be converted to numbers, say for integers intValue = Integer.parseInt(text)
I do not have enough reputation to comment but #superbob answer is almost perfect, indeed you must ensure to pass Charset.defaultCharset() as 2nd parameter like :
Files.lines(file.toPath(), Charset.defaultCharset()).count()
That's because Files.lines used UTF-8 by default and then using as it is on non default UTF-8 system can produce java.nio.charset.MalformedInputException.
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.
My question is quite simple, I want to read in a text file and store the first line from the file into an integer, and every other line of the file into a multi-dimensional array. The way of which I was thinking of doing this would be of creating an if-statement and another integer and when that integer is at 0 store the line into the integer variable. Although this seems stupid and there must be a more simple way.
For example, if the contents of the text file were:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
The first line "4", would be stored in an integer, and every other line would go into the multi-dimensional array.
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
I'm intentionally not answering this to do it for you. Try something with:
String.split
A line that says something like array[temp-1] = new int[firstLine];
An inner for loop with another Integer.parseInt line
That should be enough to get you the rest of the way
Instead, you could store the first line of the file as an integer, and then enter a for loop where you loop over the rest of the lines of the file, storing them in arrays. This doesn't require an if, because you know that the first case happens first, and the other cases (array) happen after.
I'm going to assume that you know how to use file IO.
I'm not extremely experienced, but this is how I would think about it:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
Good Luck.