example i have this numbers or arrays on my file (notepad)
2 3 4 5 7 2 6 2
2 4 6 8 9 4 8 1
I want to ask if how to read the next row. I can only read the first row using this code.
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
String lineOfNumbers = br2.readLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][i] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int location = 0;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i][i] == searchNumber)
{
location = i+ 1;
}
}
thank you in advance.
I would do somethin like this
FileReader fr = new FileReader("myFileName");
BufferedReader br = new BufferedReader(fr);
while((line=br.readLine())!=null) // as long as there are lines in the file
{
stringOfNumbers = line.split(" ");
// other code
}
Following code will Help you save all numbers in a file to memory
Scanner scanner = new Scanner(path);
List<Integer[]> integerArList = new ArrayList<Integer[]>();
while(scanner.hasNextLine()){
String lineOfNumbers = scanner.nextLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
Integer[] numbers = new Integer[stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = Integer.parseInt(stringOfNumbers[i]);
}
integerArList.add(numbers);
}
After this you can search any Integer by traversing each array in the List like this:
int searchMe = <get this from user>
int location=0;
boolean found=false;
for(Integer[] intAr: integerArList){
for(int i=0;i<intAr.length;i++){
if(intAr[i]==searchMe){
location+=(i+1)
found=true;
break;
}
}
if(found) break;
location+=intAr.length;
}
System.out.println("Location of " + searchMe +" : " +(found?location:"Not Found in Data"));
Hope this helps.
To read all lines of a text file you can do something like this:
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
ArrayList<String> listOfLines = new ArrayList<String>();
//String lineOfNumbers = "";
String line = "";
String allIndexes = "";
while ((line = br2.readLine()) != null) {
if(!line.isEmpty()){
listOfLines.add(line);
}
}
for(String lineOfNumbers : listOfLines){
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][listOfLines.size()];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][listOfLines.indexOf(lineOfNumbers)] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int locationI = 0;
int locationJ = 0;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < listOfLines.size(); j++)
if (numbers[i][j] == searchNumber)
{
locationI = i + 1;
locationJ = j + 1;
allIndexes += locationI + ":" + locationJ + " ";
}
}
}
Related
I am trying to find top k words in a "data" text file. But I cannot remove stopwords including in "stop.txt" should I do it manually adding stopwords one by one or there is a method to read stop.txt file and remove these words in data.txt file?
try {
System.out.println("Enter value of 'k' words:: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
w = new String[n];
r = new int[n];
Set<String> stopWords = new LinkedHashSet<String>();
BufferedReader SW = new BufferedReader(new FileReader("stop.txt"));
for(String line; (line = SW.readLine()) != null;)
stopWords.add(line.trim());
SW.close();
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while((sz=br.readLine())!=null){
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
uniqueLabels = getUniqLabels(words);
for(int j=0; j<n; j++){
r[j] = 0;
}
for(String l: uniqueLabels)
{
if("".equals(l) || null == l)
{
break;
}
for(String s : words)
{
if(l.equals(s))
{
count++;
}
}
for(int i=0; i<n; i++){
if(count>r[i]){
r[i] = count;
w[i] = l;
break;
}
}
count=0;
}
display(n);
} catch (Exception e) {
System.err.println("ERR "+e.getMessage());
}
Read file contents by:
List<String> stopwords = Files.readAllLines(Paths.get("english_stopwords.txt"));
Then use this for removing stop words:
ArrayList<String> allWords =
Stream.of(original.toLowerCase().split(" "))
.collect(Collectors.toCollection(ArrayList<String>::new));
allWords.removeAll(stopwords);
String result = allWords.stream().collect(Collectors.joining(" "));
Removing Stopwords from a String in Java
Following code is not giving any decrypted output
Sample:
Enter the string to be encrypted:
hello
Enter the 64 bit key
0000000000111111111100000000001111111111000000000011111111110101
The encrypted message is:
00101110100000001001010111001101101
The decrypted message is:
Can anyone tell what is wrong with the code?
import java.io.*;
class A51 {
public static void main(String args[])throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string to be encrypted:");
String msg = br.readLine();
byte[] st = null;
st = msg.getBytes("UTF-8");
msg = "";
for(byte b:st) {
msg = msg + Integer.toBinaryString(b);
}
int len = msg.length();
int s[] = new int[len];
System.out.println("\nEnter the 64 bit key");
int x[] = new int[19];
int y[] = new int[22];
int z[] = new int[23];
int i;
String str[] = br.readLine().split("");
for(i=0; i<19; i++)
x[i] = Integer.parseInt(str[i]);
for(i=0; i<22; i++)
y[i] = Integer.parseInt(str[i+19]);
for(i=0; i<23; i++)
z[i] = Integer.parseInt(str[i+19+22]);
int m = 0, t;
for(int j=0; j<len; j++) {
if(x[8]==y[10] || x[8]==z[10])
m = x[8];
else if(y[10]==z[10])
m = y[10];
if(x[8]==m) {
t = x[13]^x[16]^x[17]^x[18];
for(i=18; i>0; i--)
x[i] = x[i-1];
x[0] = t;
}
if(y[10]==m) {
t = y[20]^y[21];
for(i=21; i>0; i--)
y[i] = y[i-1];
y[0] = t;
}
if(z[10]==m) {
t = z[7]^z[20]^z[21]^z[22];
for(i=22; i>0; i--)
z[i] = z[i-1];
z[0] = t;
}
s[j] = x[18]^y[21]^z[22];
}
int enc[] = new int[len];
int dec[] = new int[len];
System.out.println("\nThe encrypted message is:");
for(i=0; i<len; i++) {
enc[i] = Integer.parseInt(Character.toString(msg.charAt(i)))^s[i];
System.out.print(enc[i]);
}
msg = "";
System.out.println("\n\nThe decrypted message is:");
for(i=0; i<len; i++) {
msg = msg + dec[i];
if(i%7==6) {
int decp = Integer.parseInt(msg, 2);
System.out.print((char)decp);
msg = "";
}
}
}
}
the array dec[] is empty
int dec[] = new int[len];
//Add values to dec
for(i=0; i<len; i++) {
msg = msg + dec[i];
if(i%7==6) {
int decp = Integer.parseInt(msg, 2);
System.out.print((char)decp);
msg = "";
}
}
you need to add values to dec[] before the loop
input:-
1
Ans kot
Output:-
kot Ans
INPUT :
the first line of the input contains the number of test cases. Each test case consists of a single line containing the string.
OUTPUT :
output the string with the words swapped as stated above.**
Code:-
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.next();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
What is wrong in my code ? above is code which i am trying.
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
this snippet of your code is only gonna reverse the sentence "word by word" not "character by character". therefore, you need reverse the string (my[j]) before you append it into the StringBuffer
Use this
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.nextLine();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.nextLine();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
Multiple things:
You are using next api which will just read your string that you type word by word and you loop until a i.e. in your example just once. So instead use nextLine api which will read whole line instead of just a word and then split by space:
String b = sc.nextLine();
You are reading input with nextInt api followed by enter, you you might sometime end up having return character when reading next token using next api. Instead use:
int a = Integer.parseInt(sc.nextLine());
You are using StringBuffer which has an overhead of obtaining mutex and hence should use StringBuilder.
Takes String input and return String in reverse order of each characters.
String reverse(String x) {
int i = x.length() - 1;
StringBuilder y = new StringBuilder();
while (i >= 0) {
y.append(x.charAt(i));
i--;
}
return y.toString();
}
public static String reverseWords(String input) {
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
You can run this code:
String[] splitted = yourString.split(" ");
for (int i = splitted.length-1; i>=0; i--){
System.out.println(splitted[i]);
}
Code:-
Scanner sc =new Scanner(System.in);
int a =Integer.parseInt(sc.nextLine());
StringBuffer result= new StringBuffer();
for (int i = 0; i <a; i++) {
String b=sc.nextLine();
String my[]= b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length-1; j >0; j--) {
r.append(my[j]+" ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
enter code here
I am trying to make this input.txt into a 2D array. I tried a few different methods. This is my latest attempt, and I seem to be stuck here... Any help is much appreciated.
input.txt structure: SCI2000/Science/1200/10/C --> There are 23 rows and 5 columns. I'd also like to have a title made for each column.
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
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();
String[][] input = new String[23][5];
String[] tokens = everything.split("/");
for(String str : tokens)
System.out.print(str);
Just the main processing part (not tested):
int columns = 5;
String[] row = String[columns];
int j = 0;
while ((line = br.readline) != null) {
row = line.split("/");
for(int i=0; i<row.length; ++i) {
input[j,i] = row(i);
}
++j;
}
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
String[][] input = new String[24][5]; // 1 row for title, 23 rows for data
// add title
input[0] = new String[]{"title1", "title1", "title1", "title1", "title1"};
String line = br.readLine();
int row = 1; // update here
while ( (line = br.readLine())!= null ) {
input[row++] = line.split("/");
}
// print all data
for ( int i = 0; i < input.length; i++) {
for ( int j = 0; j < input[i].length; j++ )
System.out.print(input[i][j] + " ");
//new line
System.out.println();
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to print 2D Array from .txt file in Java
text file is:
8.00 28.00
18.00 28.00
8.00 23.00
12.00 20.00
15.00 30.00
... etc (many more lines)
i am reached upto:
public class Asgn2backup {
public static double[][] matrix;
public static void main(final String[] args) throws IOException {
System.out.print("Enter the name of the file: ");
final String fileName = readInput();
final BufferedReader br = new BufferedReader(
new FileReader(fileName + ".txt"));
String line;
int order = 0;
int rowIndex = 0;
int counter = 0;
while ((line = br.readLine()) != null) {
counter++;
if (counter == 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
}
if (counter == 2) {
final String source = line;
System.out.println("source: " + source);
}
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
final StringTokenizer theLine =
new StringTokenizer(line, ", ");
int colIndex = 0;
while (theLine.hasMoreTokens()) {
final String st = theLine.nextToken();// .trim();
matrix[rowIndex][colIndex] = Double.parseDouble(st);
colIndex = colIndex + 1;
}
rowIndex = rowIndex + 1;
}
}
for (int x = 0; x < matrix.length - 1; x++) {
for (int p = 0; p < matrix.length - 1; p++) {
System.out.print(matrix[x][p] + " ");
}
}
br.close();
}
private static String readInput() {
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
return in.readLine();
} catch (final IOException e) {
}
return "";
}
}
but it gives numberformatexception runtime error.
give me complete solution.
pls help me.
The parser does not fit the input file at all. In each condition you try to parse the entire line as a single integer value. This will cause NumberFormatExceptions.
Example:
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line); // line = "8.00 23.00" < not an integer
The lines contain float or double values. So you'll have to split the line around multiple whitespaces and parse the two fragments with Double.parseDouble(split[<0|1>]) to double values.