what's the difference between two codes - java

I'm trying to submit the second code on spoj but it gives wrong answer but the first one is accepted although i think that the logic of the two codes are the same.
public class Main {
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader r = new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String s;
while (!(s = r.readLine()).startsWith("42"))
System.out.println(s);
}
}
and
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if (n != 42) {
System.out.println(n);
}
}
}

There is no loop in your second code. Try your code using the following input data:
1
2
88
42
99
Your second code is going to process only first line on the input (i.e. 1). Here is the working example of your code: http://ideone.com/Qr1q3N
You can, for example, introduce a loop in the following way:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
while ((n = Integer.parseInt(br.readLine())) != 42) {
System.out.println(n);
}
}
}
Here you can see this code in action: http://ideone.com/z8H4fP

Related

How to split file input into 2 different arrays java

How do I split a file input text into 2 different array? I want to make n array for the names, and an array for the phone numbers. I managed to do the file input, but ive tried everything and cant seem to split the names and the numbers, then put it into 2 different arrays. Im noob pls help
here is how the phonebook.txt file looks like
Bin Arry,1110001111
Alex Cadel,8943257000
Poh Caimon,3247129843
Diego Amezquita,1001010000
Tai Mai Shu,7776665555
Yo Madow,1110002233
Caup Sul,5252521551
This Guy,7776663333
Me And I,0009991221
Justin Thyme,1113332222
Hey Oh,3939399339
Free Man,4533819911
Peter Piper,6480013966
William Mulock,9059671045
below is my code
import java.io.*;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class demos {
public static void main(String[] args){
FileInputStream Phonebook;
DataInputStream In;
int i = 0;
String fileInput;
try
{
Phonebook = new FileInputStream("phonebook.txt");
FileReader fr = new FileReader("phonebook.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
fulltext += buffer;
// System.out.println(buffer);
String names = buffer;
char [] Y ;
Y = names.toCharArray();
System.out.println(Y);
}}
catch (FileNotFoundException e)
{
System.out.println("Error - this file does not exist");
}
catch (IOException e)
{
System.out.println("error=" + e.toString() );
}
For a full functionnal (rather than imperative) solution I propose you this one :
public static void main(String[] args) throws IOException {
Object[] names = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[0]).toArray();
Object[] numbers = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[1]).toArray();
System.out.println("names in the file are : ");
Arrays.stream(names).forEach(System.out::println);
System.out.println("numbers in the file are : ");
Arrays.stream(numbers).forEach(System.out::println);
}
output
names in the file are :
Bin Arry
Alex Cadel
Poh Caimon
Diego Amezquita
Tai Mai Shu
Yo Madow
Caup Sul
This Guy
Me And I
Justin Thyme
Hey Oh
Free Man
Peter Piper
William Mulock
numbers in the file are :
1110001111
8943257000
3247129843
1001010000
7776665555
1110002233
5252521551
7776663333
0009991221
1113332222
3939399339
4533819911
6480013966
9059671045
As you can see functionnal programming is short and smart …. and easy when you're accustomed
You could simplify it if you are using Java 8:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
/**
* For each line, split it on the comma and send to splitNameAndNum()
*/
public static void main(String[] args) throws IOException {
Files.lines(new File("L:\\phonebook.txt").toPath())
.forEach(l -> splitNameAndNum(l.split(",")));
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
And in Java 7:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("L:\\phonebook.txt")));
String line;
while ((line = br.readLine()) != null) {
splitNameAndNum(line.split(","));
}
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}

Java 8 "Missing return type" error for lambda expression

I am new to Java 8 and trying to understand the concepts. I am getting
Missing return type
error for the Lambda expression I am passing to ReadTheFile method.
BufferReaderProcessor
package java8.programs;
import java.io.BufferedReader;
import java.io.IOException;
#FunctionalInterface
public interface BufferReadderProcessor {
String process(BufferedReader br) throws IOException;
}
MainJava
package java8.programs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class MainJava {
public static void main(String[] args) throws IOException {
MainJava obj = new MainJava();
String message = obj.ReadTheFIle((BufferedReader br) -> {
while (br.readLine()!=null)
br.readLine();
});
System.out.println(message);
}
public String ReadTheFIle(BufferReadderProcessor bp) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("G:\\DemoJavaFile.txt")));
return bp.process(br);
}
}
Your lambda expression implements the BufferReaderProcessor's String process(BufferedReader br) method, so it should return a String.
For example, assuming you wish to return the data you read from the BufferedReader :
String message = obj.ReadTheFIle((BufferedReader br) -> {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.toString();
});

I'm trying to read a CSV file and display it in excel as a csv file

***I'm having error that states:
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
I solved the previous issue but I'm now getting this error: C:\Program Files\Java\jre1.8.0_60\bin\javaw.exe (Nov 8, 2015, 7:41:12 PM)
When attempting to run this code:***
package filtermovingaverage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class Main {
//public static void main(String[] args){
private static double freqS = 100;
static ArrayList<Double> sec = null;
private static double[] pressure = new double[20481];
void func() throws IOException
{
BufferedReader read = new BufferedReader(new FileReader(new File("C:\\Users\\KwakuK\\Downloads\\smith2.csv")));
String currentLine = new String();
currentLine = read.readLine();
int i = 0;
//make some computation
while((currentLine = read.readLine()) != null)
{
String[] numbers = currentLine.split(","); // split the string into sub strings
if(numbers.length >= 3)
{
System.out.println("currentLine: " + " " + currentLine);
pressure[i++] = Double.parseDouble(numbers[2]); // when you do the 2, it's the third column which is the pressure
}
}
}
public static void setupFirstPlot() throws FileNotFoundException{
sec = new ArrayList<Double>();
double ws = 1/freqS;
double n = (pressure.length)*ws;
for(double i = 0; i < n; i = i + ws){
sec.add(i);
}
PrintWriter pw = new PrintWriter(new File("plot13.csv"));
for(int i = 0; i < pressure.length; i++){
pw.write(sec.get(i)+","+pressure[i]+"\n");
}
pw.close();
}
public static void main(String[] args) throws FileNotFoundException{
setupFirstPlot();
System.out.println();
}
}
Try adding package filtermovingaverage; to the top of this java file.

geting a multiline text with scanner class in java

In a part of my university project I have to get a text with some lines then saving it in a string or a string array.My problem is that in scanner class using methods gets only one line of the input. So I cannot get the other lines.please help me.
public class Main {
public static void main(String[] args) {
java.util.Scanner a = new java.util.Scanner(System.in);
String b = "";
while (a.hasNextLine()) {
b += a.nextLine();
}
}
}
You can try to use isEmpty to detect an enter-only input.
UPDATED:
If your input also contain a blank line, then you may specify another terminator character(s); instead of only an empty string.
public class Main {
public static void main(String[] args) {
//for example ",,"; then the scanner will stop when you input ",,"
String TERMINATOR_STRING = ",,"
java.util.Scanner a = new java.util.Scanner(System.in);
StringBuilder b = new StringBuilder();
String strLine;
while (!(strLine = a.nextLine()).equals(TERMINATOR_STRING)) {
b.append(strLine);
}
}
}
If you are building your program from command line, then there's something called "input redirection" which you can use. Here's how it works:
Let's suppose your program is:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (System.in))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
System.out.println ("Total lines: " + lines.size ());
}
}
Now suppose you have input for your program prepared in a file.
To compile the program you'd change the current directory of terminal/command prompt to the program directory and then write:
javac ScanningMultiline.java
And then to run, use input redirection like:
java ScanningMultiline < InputFile.txt
If your InputFile.txt is in another directory, just put its complete path instead like:
java ScanningMultiline < "/Users/Xyz/Desktop/InputFile.txt"
Another Approach
You can try reading your input directly from a file. Here's how that program would be written:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (Paths.get (inputFile)))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
catch (IOException e)
{
e.printStackTrace ();
}
System.out.println ("Total lines: " + lines.size ());
}
}
This approach reads directly from a file and puts the lines from the file in a list of String.
Another Approach
You can read the lines from a file and store them in a list in a single line as well, as the following snippet demonstrates:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ScanningMultiline
{
public static void main (String[] args) throws IOException
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = Files.readAllLines (Paths.get (inputFile));
}
}
Yohanes Khosiawan has answered a different approach so I'm not writing that one here.

Reversing Lines With Recursion Java

I am just trying to reverse the lines which I receive from the input, but every single time I run my code, the output.txt file is empty. What am I missing?
It appears mostly correct to me, even the recursion passage.
Thanks
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception{
input = new BufferedReader(new FileReader(args[0]));
output = new PrintWriter(new FileWriter(args[1]));
reverse(input, output);
}
public static void reverse( BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if(line != null) {
reverse (input, output);
output.println(line);
}
}
}
Close the PrintWriter in your main method:
output.close();
do output.flush() and check whether it works!

Categories