check two different files in java and compare them [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have two file .First the property file and second the content file
first file
properties
{
"rowcount" : "3"
"delim" : "|"
}
second file
a|b|c
d|e|f
g|h|i
i want to read both the file and check whether the second file follows the rule .(the structure of the first file will always be similar )

Well, first of all i think the first file should be a properties.json with this syntax:
{
properties: {
rowcount: "3",
delim: "|"
}
}
With a JSONParser you can read the JSON file and map it in a Object.
Then with a FileReader you can deal with the second file. For the validation part i think that a regular expression and a rowcount from the FileReader can easily solve the problem.

For the first part, simply read in the rowcount number from the first file and compare to the line count from the second file.
For the second part, read in delim and then use a Scanner or similar to read the second file using delim as your delimiter. If you only want a single character in between each delimiter, then test for this as you read the file, and throw an exception if you see more than a single character being read in.
From the example link:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
char[] chars = new char[100]; //If you know how many you want to read
//(if not, use an ArrayList or similar)
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Set delimiters to newline and pipe ("|")
//Use newline character OR (bitwise OR is "|") pipe "|" character
//since pipe is also OR (thus a meta character), you must escape it (double backslash)
src.useDelimiter(src.useDelimiter(System.getProperty("line.separator")+"|\\|");
// Read chars
for(int i = 0; src.hasNext(); i++) {
String temp = src.next();
if(temp.length != 1)
System.out.println("Error, non char"); //Deal with as you see fit
chars[i] = temp.charAt(0); //Get first (and only) character of temp
}
fin.close();
//At this point, chars should hold all your data
}
}

Related

Java How to Read Data From a String (stringstream equivalent) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have a String (call it s) with the following format:
[String] [String] [double] [int]
for example,
"YES james 3.5 2"
I would like to read this data into separate variables (a String, a String, a double, and an int)
Note that I come from a C++ background. In C++, I would do something like the following:
std::istringstream iss{s}; // create a stream to the string
std::string first, second;
double third = 0.0;
int fourth = 0;
iss >> first >> second >> third >> fourth; // read data
In Java, I came up with the following code:
String[] sa = s.split(" ");
String first = sa[0], second = sa[1];
double third = Double.parseDouble(sa[2]);
int fourth = Integer.parseInt(sa[3]);
However, I will have to do this to many different inputs, so I would like to use the most efficient and fastest way of doing this.
Questions:
Is there any more efficient/faster way of doing this? Perhaps a cleaner way?
Try it like this. Scanner's constructor can take a string as a data source.
Scanner scan = new Scanner("12 34 55 88");
while (scan.hasNext()) {
System.out.println(scan.nextInt());
}
prints
12
34
55
88
As it has been mentioned in the comments, if this is coming from keyboard (or really from an input stream) you could use Scanner class to do so. However, from input sources other than keyboard, I will not use Scanner but some other method to parse strings. For example, if reading lines from a file, you may want to use a Reader instead. For this answer, I will assume the input source is the keyboard.
Using Scanner to get the input
Scanner scanner = new Scanner(System.in);
System.out.print("Provide your input: ");
String input = scanner.nextLine();
input.close();
Break the String into tokens
Here you have a few options. One is to break down the string into substring by splitting the input using white space as a delimeter:
String[] words = input.split("\\s");
If the order of these substrings is guaranteed, you can assign them directly to the variables (not the most elegant solution - but readable)
String first = words[0];
String second = words[1];
double third = words[2];
int fourth = words[3];
Alternatively, you can extract the substrings directly by using String#substring(int) and/or String#substring(int, int) methods and test whether or not the obtained substring is a number (double or int), or just simply a string.

How to correct this text processing programme? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class TextProcessing
{
public static void main(String[] args)
{
String sentence, wordToBeTargeted, wordToBeReplaced, output;
boolean wordToCheck;
Scanner myInput = new Scanner(System.in);
sentence = myInput.nextLine();
do
{
wordToCheck = true;
System.out.println("Please enter the word for replacement:");
wordToBeTargeted = myInput.nextLine;
if(sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1)
{
wordToCheck = false;
System.out.println("This word cannot be found in the sentence!")
}
else
{
System.out.println("Please enter the word you would like to replace with:");
wordToBeReplaced = myInput.nextLine();
}
}while(wordToCheck = false);
}
}
}
Write a file named TextProcessing.java that will replace all occurrences of a word in a string with another word
The expected outcome is like this:
I won't write the code out - you should still get something out of the exercise, but will give some direction. The first approach that comes to mind:
Split the first input on ' ' into a list
Iterate through the list, conditionally changing values based based on two input strings
As you're iterating you can either output into a new string / stringbuilder, or directly write to console depending on the requirements

String arrays of capacity 5 will only display first 4 elements (java - scanner class) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm new in java programming and was learning input via scanner class. My program accepts a string array of capacity 5, and displays it back to the user.
However, the array is only accepting 4, and I can't figure out why. Any help would be appreciated.
My code
Accepting string array
String n[] = new String[5];
for (int i = 0 ; i<5 ; i++)
{
n[i] = sc.nextLine();
}
Displaying the string array
for(int i=0 ; i<5 ; i++)
{
System.out.println(n[i]);
}
The 5th string is being accepted and printed as blank for some reason, as in instead of 5 only 4 strings are being accepted and printed.
Maybe you read from a file, and the last line does not end with a line break.
From a Scanner you may first test whether a next line is available:
String[] n = new String[5];
for (int i = 0; i < 5; i++) {
if (!sc.hasNextLine()) {
System.out.println("Failing to read line at index " + i);
break;
}
n[i] = sc.nextLine();
}
Notice that String[] n is the usual way to write an array variable. String n[] is for C programmers.
It would be helpful if you provided information on what your input source is. However, sc.nextLine() always progresses the scanner to the next line (excluding any line separators at the end of the line).
Your code is correct given (for example) an input file such as "test.txt":
Line1
Line2
Line3
Line4
Line5
I would make sure there's no spaces between your input and that you don't accidentally call sc.nextLine() (or any of the scanner next methods) somewhere earlier in your code.

Using java i m trying to replace i for e ;e for a and a for i from user input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Using Java I’m trying to replace i for e ;e for a and a for i from user input. For example, input:
The ear is big.
output from the program is:
Tha air es beg.
Both upper case and lower case of aforementioned letters must be encrypted.
import java.util.Scanner;
public class test{
public static void main(String[] Args);
System.out.println("Enter String:");
new Scanner=Scanner kb(System.in);
String old=kb.nextLine();
String modified=old.replaceAll("i","e").replaceAll("e","a").replaceAll("a","i").trim();
System.out.println( "\n The Output is="+modified );
}
}
In addition to a number of typos and syntax errors, you are replacing the characters you then test for replacement. I think it would be better to eschew a regex here, and use a Map<Character, Character> and StringBuilder like
public static void main(String[] args) {
System.out.println("Enter String:");
Scanner kb = new Scanner(System.in);
String old = kb.nextLine();
StringBuilder sb = new StringBuilder();
Map<Character, Character> map = new HashMap<>();
map.put('i', 'e');
map.put('e', 'a');
map.put('a', 'i');
for (char ch : old.toCharArray()) {
if (map.containsKey(ch)) {
sb.append(map.get(ch));
} else {
sb.append(ch);
}
}
System.out.println("\n The Output is=" + sb.toString());
}
And add the appropriate import(s) after package at the top.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
Your problem is that you are replacing letters that already have been replaced once and should not be replaced again. I think your replcements go through the following steps:
The ear is big.
The ear es beg.
Tha aar as bag.
Thi iir is big.
The solution is to go through the sentence from left to right. In this way you can make sure you only substitute each letter once (at most).
Since you cannot substitute the letter at a specific index of a String, you need to convert your String to either a char array or a StringBuilder first. Then loop over it. Either a series of if-else statements or s switch statement can be used to make the right substitution. If you chose a char array, convert it back to a String before printing it.
Also remember to check for all of aAeEiI since both uppercase and lowercase letters should be encrypted.

Read input from text file in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to read input from a text file in java. I have a text file as follows.
5
4
abcd
6
8
defgh
10
I want to read each character from file as a separate entity and work on that character individually like storing 4 in database separating abcd as a b c d and work on them individually.
What are the various ways to do it. What is the most efficient way.
The easy way (and short) if you use Java 7:
List<String> lines = Files.readAllLines(Paths.get("path to file"), StandardCharsets.UTF_8);
It will put all file data to list where list item represents one row
Use read line if your file has new lines.
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
If you want to use each character individually, then using a Scanner might be the way to go:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SOExample {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("myfile.txt"));
sc.useDelimiter("");
while (sc.hasNext()) {
String s = sc.next();
if (s.trim().isEmpty()) {
continue;
}
System.out.println(s);
}
sc.close();
}
}
output:
5
4
a
b
c
d
6
8
d
e
f
g
h
1
0

Categories

Resources