If I have a while loop that goes through a file and prints the numbers, how would I make it to where it only prints the very last number.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
This is the output I'm currently getting. How would I make get it to where it would just print out 19
And how would I get it to work to where the numbers start at 1 instead of 0?
Currently my loop looks like this:
if (math == last){
System.out.println(Score++);
}
math is another method which computes equations, and last is the answer inputed from a file, and the loop currently just checked if the math matches the inputed answer in order to "grade" the problems.
I can't use arrays, try/catch, or regex.
Just read through the file normally and store each line in a temporary variable. Once the reader finishes reading, print out the temporary variable.
public class ReaderExample {
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
String copy = "";
while((line = br.readLine() )!= null){
copy = line;
}
System.out.println(copy);
}
}
Using a Scanner
The same principle applies with a Scanner:
public class ReaderExample {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("input.txt"));
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
System.out.println(line);
}
}
Without Invoking Scanner
public String getLast(Scanner scanner){
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
return line;
}
Related
I tried to start using BufferedReader instead of Scanner. While coding for a question on codechef (SMRSTR), I tried taking space separated inputs by using StringTokenizer but it is raising exception i.e NumberFormatException. I found some question on StackOverflow regarding it but I think my problem is different, so I posted one.
Input: 1
2 3
2 3
5 100 8
I am getting:
Exception in thread "main" java.lang.NumberFormatException: For
input string: "2 3"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at A.main(A.java:11)
I am getting first input t correctly from br.readLine();
But next inputs n,q are giving the mentioned exception. I think the problem is in the nextToken from StringTokenizer, but still not getting it clearly.
Here is the code:
import java.io.*;
import java.util.*;
class A{
public static void main(String arg[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer s = new StringTokenizer(br.readLine());
int t= Integer.parseInt(br.readLine());
while(t-->0)
{
int n,q,i;
n=Integer.parseInt(s.nextToken());
q=Integer.parseInt(s.nextToken());
int D[]= new int[n];
int Q[]=new int[q];
long x=1;
for(i=0;i<n;i++)
{
D[i]=Integer.parseInt(s.nextToken());
x=x*D[i];
}
for(i=0;i<q;i++)
{
Q[i]=Integer.parseInt(s.nextToken());
if(x>1000000000)
Q[i]=0;
else
Q[i]=(int)(Q[i]/x);
}
for(i=0;i<q;i++)
System.out.print(Q[i]+" ");
System.out.println("");
}
}
}
Assuming your first line is a single number and your second line a string of space separated numbers (if not, edit your question with your actual input)
I think you want to read t this way:
int t = Integer.parseInt(s.nextToken());
Then read your next line into your tokenizer
s = new StringTokenizer(br.readLine());
The code before the while loop should be:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer s = new StringTokenizer(br.readLine());
int t = Integer.parseInt(s.nextToken());
s = new StringTokenizer(br.readLine());
EDIT
You need to read each line in the tokenizer before using the next Int method. This should work.
Input:
1
2 3
2 3
5 100 8
Output:
0 16 1
Working code:
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read first line in tokenizer
StringTokenizer s = new StringTokenizer(br.readLine());
//parse t
int t = Integer.parseInt(s.nextToken());
// read second line in tokenizer
s = new StringTokenizer(br.readLine());
while(t-->0) {
int n,q;
// parse n and q (2, 3)
n=Integer.parseInt(s.nextToken());
q=Integer.parseInt(s.nextToken());
int D[]= new int[n];
int Q[]=new int[q];
long x=1;
// read third line in tokenizer
s = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++) {
D[i]=Integer.parseInt(s.nextToken());
x=x*D[i];
}
// read fourth line in tokenizer
s = new StringTokenizer(br.readLine());
for(int i=0;i<q;i++) {
Q[i]=Integer.parseInt(s.nextToken());
if(x>1000000000)
Q[i]=0;
else
Q[i]=(int)(Q[i]/x);
}
for(int i=0;i<q;i++)
System.out.print(Q[i]+" ");
System.out.println("");
}
}
Write a program that takes input of integers N and M (separated by space) on first line, followed by an array of N integers on second line (separated by space) and then M more lines, each with an integer. For each of the of those ​M​ integers, output "True" (without quotes), if that number is present in the array N. Output "False" (without quotes) otherwise.
Constraints:
0 < N < 20,000
0 < M < 15,000
so far i have,
import java.io.*;
class Main
{
static int arr[];
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
str="\\s+";
while((str=input.readLine())!=null)
String[] numberList = input.split("\\s+");
}
}
}
the intended input e.g
4 2
99 12 10 23
23
25
and output:
Output:
True
False
and the explanation is as follows
Explanation: An array of size 4 is taken, followed by 2 lines. 23 outputs True, since 23 is present in above array. 25 outputs False because it was not in the array of N numbers.
however i am having some problems with the being able to read in from multiple lines and changing it to arrays of int.
Any help guys?
Cheers
****UPDATE******
so the new code i have now is
/* package whatever; // don't place package name! */
import java.io.*;
import java.util.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;
if ((line = stdin.readLine()) != null) {
String[] input = line.split("\\s+");
for(int i=0;i<input.length;i++){
System.out.println(input[i]);
}
// break;
}
}
}
but the loop keeps getting stuck and wont exit. I cant add a trivial character to the end of the string to make it exit. any suggestions?/
Here's my code:
public static void main(String[] args) throws IOException {
writeToFile ("c:\\scores.txt");
processFile("c:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner reader = new Scanner (System.in);
int Num;
System.out.println ("Please enter 7 scores");
for (int i = 0; i < 7; i++) {
Num= reader.nextInt ();
outputWriter.write(Num);
if(i!=6) {
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException
{
double sum=0.00;
double number;
double average;
int count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
while((line = inputReader.readLine()) != null)
{
number= Double.parseDouble(line);
System.out.println(number);
count ++;
sum += (number);
System.out.print ("Total Sum: ");
System.out.println(sum);
System.out.print("Average of Scores: ");
average=sum/count;
System.out.println(average);
}
inputReader.close();
}
This is what my output is.
Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at writefile.Writefile.processFile(Writefile.java:52)
at writefile.Writefile.main(Writefile.java:19)
Java Result: 1
I do not know how to fix this. I'm not sure how to fiz the floating decimal or empty string error.The file has weird symbols in it, no integers. How do I fix this? Please be specific please as I'm only a beginner at Java.
outputWriter.write(1); does not mean outputWriter.write("1");
you need change outputWriter.write(Num); to outputWriter.write(""+Num);
please refer outputstream.write(int)
The error happens because line is an empty string at some point, test for this before parsing the string:
while ((line = inputReader.readLine()) != null) {
if (line.trim().length() > 0) {
number = Double.parseDouble(line);
// rest of loop
}
}
That is, assuming that the line contains only numbers. If there are other characters, you'll have to perform a more careful validation before parsing the line.
The file has weird symbols in it, no integers.
From BufferedWriter#write(int):
Writes a single character.
So it's not writing the int value you're sending to it, instead its character representation.
It would be better if you just write the numeric value as String and then retrieve it as String and parse it. In your writeToFile method, modify this part
for (int i = 0; i < 7; i++) {
Num = reader.nextInt ();
outputWriter.write(Integer.toString(Num));
if(i!=6) {
outputWriter.newLine();
}
}
here is a very simple code, in which i am trying to take input from keyboard in a loop. For every input, the loop is automatically running two extra times and taking the values 13 and 10, no matter what i give as input. can you please point out what i am doing wrong.
CODE:
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
boolean loop_cond=true;
int n=1;
while(loop_cond==true)
{
try
{
System.out.print("input : ");
n=br.read();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.print(n+"\n");
}
} // end Main
OUTPUT :
input : 6
54
input : 13
input : 10
input : 9
57
input : 13
input : 10
input : 1
49
input : 13
input : 10
input :
Those are probably \r\n values. Try Scanner to take in values.
Scanner input = new Scanner(System.in);
int i = input.nextInt();
Change
n=br.read();
to
n = Integer.parseInt(br.readLine());
But I would recommend you to use Scanner class to avoid the Integer conversion.
Essentially I have a file of lines of integers. Each line has 9 digits. And I want to read the file. And then input each line into its an array. I want the array to be the same one each time. As I am going to do some processing to the array created from the first line. And then process the same array using a different line.
My input file is as follows:
8 5 3 8 0 0 4 4 0
8 5 3 8 0 0 4 2 2
And the current code that I am using is:
BufferedReader br = new BufferedReader(new FileReader("c:/lol.txt"));
Scanner sc = new Scanner(new File("c:/lol.txt"));
String line;
while (sc.hasNextLine()){
line = sc.nextLine();
int k = Integer.parseInt(line);
Now clearly I should be doing something more, I am just not really sure how to go about it.
Any help is greatly appreciated.
Try:
import java.util.Scanner;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("c:/lol.txt"));
while (sc.hasNext()) {
String line = sc.nextLine();
// get String array from line
String[] strarr = line.split(" "); // attention: split expect regular expression, not just delimiter!
// initialize array
int[] intarr = new int[strarr.length];
// convert each element to integer
for (int i = 0; i < strarr.length; i++) {
intarr[i] = Integer.valueOf(strarr[i]); // <= update array from new line
}
}
}
}
Of course, you should handle exception instead to pass it.