print specific characters in an array of strings - java

I need to print specific indexes of strings in an array, for example
String[] words = {car, bike, truck};
print words[0][0] and the result would be c and print words[0][1] = a.
Also i have to read the array from a text file. What i have so far will print the first word of the array.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
public class DemoReadingFiles
{
public static void main (String[] args)
{
String[] words = readArray("words.txt");
System.out.println(words[0]);//i can get it to print specific elements
}
public static String[] readArray(String file)
{
int ctr = 0;
try
{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1)
{
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e)
{
}
return null;
}
}

public static void main(String[] args) {
String[] words = {"cars", "bike", "truck"};
System.out.println("Specific character print:" + words[0].charAt(0));
System.out.println("Multi character selection printed as follows:" + words[0].substring(1, words[0].length() - 1));
}
Output:
Specific character print:c
Multi character selection printed as follows:ar

Related

Counting the frequency of n-grams in a sample text file

So, I'm implementing a Markov random text generator in Java, and I've gotten as far as plucking out the n-grams in the text file, but now I'm struggling to write a class that gives the number of occurrences of the n-grams in the text (and eventually the probability).
This is the code I have so far. It's a little messy but this is a rough draft.
//here's the main file, where I parse the text and create a new n-gram object with the given text
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Markov {
public static String readCorpusToString(File fileName) {
String corpus = " ";
try {
corpus = new String(Files.readAllBytes(Paths.get(String.valueOf(fileName))));
}
catch (IOException e) {
e.printStackTrace();
}
return corpus;
}
public static void main(String[] args) {
File text = new File(args[0]);
String corpus = readCorpusToString(text);
//System.out.println(corpus);
Ngram test = new Ngram(3, corpus);
for ( int i = 0; i <= corpus.length(); i++) {
System.out.println(test.next());
}
}
}
and here's the class for my n-gram object
import java.util.Iterator;
public class Ngram implements Iterator<String> {
String[] words;
int pos = 0, n;
public Ngram(int n, String str) {
this.n = n;
words = str.split(" ");
}
public boolean hasNext() {
return pos < words.length - n + 1;
}
public String next() {
StringBuilder sb = new StringBuilder();
for (int i = pos; i < pos + n; i++) {
sb.append((i > pos ? " " : "") + words[i]);
}
pos++;
return sb.toString();
}
public void remove() {
throw new UnsupportedOperationException();
}
}

what wrong with my code always print answer : null+word,what is null?

We have file with a few words, try safe word with word have 2,4,6 or 8 letters in array but then save in screen write null and null+good word.
What did I write wrong, and why does it show null?
public static void lyginis () throws IOException {
Path path = Paths.get("words.txt");
Scanner scanner = new Scanner(path);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner1 = new Scanner(path);
String[] atrinkti = new String[kiek];
String scan = "";
for (int i = 0; i < kiek; i++) {
scan = scanner1.next();
if (scan.length() % 2 == 0) {
atrinkti[i] += scan ;
}
System.out.println(atrinkti[i]);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner2 = new Scanner(file);
String[] atrinkti = new String[kiek];
String word = "";
for (int i = 0; i < kiek; i++) {
word = scanner2.next();
if (word.length() % 2 == 0) {
atrinkti[i] = word;
System.out.println(atrinkti[i]);
}
}
}
}
Output
$ cat words.txt
hi
hello
whats up
chicken
duck
goose
$ javac Hello.java; java Hello
hi
up
duck
The issues were:
Path was used instead of File
The += was used within the if statement instead of just =
The System.out.println() function was called outside of the if statement so when the word's length was not divisible by 2, the current array element would print the default initialized value of the array of null

JAVA Reversing a string on multiple lines output

Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...
Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.
You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();

How can I print my array in a certain way? [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
So I'm wanting to print my arrays in a list. That will look like this.
Word: Count:
Myths 2
Of 15
Babylonia 25
I can't seem to figure out how to print it the correct way, here is the code I have so far. Any help is appreciated, thanks!
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Program6 {
static String[] stringArray = new String[100];
static int[] intArray = new int[100];
static String fileName = "myths.txt";
static int currentWordIndex = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
while (input.hasNext()){
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if(stringArray[i].equals(word)){
alreadyExists = true;
intArray[i]++;
break;
}
}
if(!alreadyExists && currentWordIndex <100){
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
}
}
Use a format and use a loop
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word:\t\tCount:");
for (int i = 0; i < stringArray.lengthl i++){
System.out.printf("%s\t\t%d\n", stringArray[i], intArray[i]);
}
Edit with right aligntment
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < array1.length; i++) {
System.out.printf("%10s%10d", array1[i], array2[i]);
System.out.println();
}
Edit: Using a method for other books
public static void main(String[] args) throws FileNotFoundException{
printCounts("myth.txt", "Babylonia and Assyria");
System.out.println();
printCounts("someOther.txt", "Some Other Title");
System.out.println();
printCounts("another.txt", "Another Title");
System.out.println();
}
public static void printCounts(String filename, String title) throws FileNotFoundException {
String[] stringArray = new String[100];
int[] intArray = new int[100];
int currentWordIndex = 0;
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if (stringArray[i].equals(word)) {
alreadyExists = true;
intArray[i]++;
break;
}
}
if (!alreadyExists && currentWordIndex < 100) {
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println(title);
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < stringArray.length; i++) {
System.out.printf("%10s%10d", stringArray[i], intArray[i]);
System.out.println();
}
}
When you are doing
System.out.println();
it is actually printing a new line at the end of your output.
Try using
System.out.print("foo ");
System.out.println("bar");
Have look at this page which explains the use of System.printf to align columns.
System.out.printf( "%-15s %15s %n", heading1, heading2);
Your arrays have 100 elements, so lots of Zeros get printed, use Arrays.copyOf to create smaller arrays.
For table format, use printf.
So you should replace the following code:
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
with:
String[] stringArray2 = Arrays.copyOf(stringArray, totalWordCount);
int[] intArray2 = Arrays.copyOf(intArray, totalWordCount);
stringArray = null;
intArray = null;
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("\n%15s%15s", "Word:","Count:");
for (int i = 0; i < stringArray2.length; i++){
System.out.printf("\n%15s%15d", stringArray2[i], intArray2[i]);
}
You have to right justify your columns. According to this stackoverflow question, columns left justified with a negative sign in front of them and right justfified without. You want your print statement to look something like this:
System.out.printf("%60s %3d", stringArray[i], intarray[i]));
You can vary the column width this way.
In addition: Someone mentioned you can avoid printing a line at the end of each statement by using print instead of println.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Program6 {
static String fileName = "myths.txt";
private static Scanner input;
public static void main(String[] args) throws FileNotFoundException {
input = new Scanner(new File(fileName));
Map<String, Integer> map = new HashMap<String, Integer>();
while (input.hasNext()){
String word = input.next();
if ( map.containsKey(word) ){
int temp = map.get(word) + 1;
map.put(word, temp);
} else {
map.put(word, 1);
}
}
// get all the set of keys
Set<String> keys = map.keySet();
// iterate through the key set and display key and values
System.out.printf("%-10s\t\t%s\n", "Word", "Count:");
for (String key : keys) {
System.out.printf("%-10s\t\t%d\n", key, map.get(key));
}
}
}

How to input relation into two dimensional array?

I have a problem in my project math.
My project is to write a program that reads a set of elements and its relations. Your input data will be from a text file. (SetRelation).
{1,2,3} {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
I have no problem reading the text file into the program but I'm stuck when I want to try to put the relation into the two dimensional array.
For example: {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
The two dimensional array would have to be like this:
col[0][1][2]
[0] 1 1 1
[1] 1 1
[2] 1
I don't know how to set one into two dimensional array because there are various relations in the text file.
This is my coding.
import javax.swing.*;
import java.util.ArrayList;
import java.io.*;
import java.util.StringTokenizer;
import java.lang.*;
import java.util.*;
public class tests
{
public static int s1[][];
public static int s2[][];
public static int s3[][];
public static int s4[][];
public static int s5[][];
public static int s6[][];
public static int s7[][];
public static int s8[][];
public static int s9[][];
public static int s10[][];
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader infile = null;
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();
ArrayList arr4 = new ArrayList();
try
{
infile = new BufferedReader (new FileReader ("numbers.txt"));
String indata = null;
while ((indata = infile.readLine())!= null)
{
StringTokenizer st = new StringTokenizer(indata," ");
String set = st.nextToken();
arr1.add(set);
String relation = st.nextToken();
arr2.add(relation);
}
for(int i =0; i < arr2.size(); i++)
{
String r = arr2.get(i).toString();
String result = r.replaceAll("[{}(),; ]", "");
arr3.add(result);
}
for(int i = 0; i < arr3.size(); i++)
{
System.out.println(arr3.get(i).toString());
}
for(int i =0; i < arr1.size(); i++)
{
String s = arr1.get(i).toString();
String result = s.replaceAll("[{}(),; ]", "");
arr4.add(result);
}
int set1 = Integer.parseInt(arr4.get(0).toString());
String ss1 = arr4.get(0).toString();
int a = ss1.length();
s1 = new int[a][a];
int sA[][];
/*for(int row=1;row< a;row++)
{
for(int col=0;col < a;col++)
{
sA = new int[row][col];
int firstNo = Integer.parseInt(arr3.get(row).toString());
int secondNo = Integer.parseInt(arr3.get(col).toString());
sA = new int [firstNo][ secondNo] ;
System.out.print(sA);
}
System.out.println();
}*/
char arrA;
char indOdd=' ',indEven=' ';
char[] cArr = arr3.get(0).toString().toCharArray();
//System.out.println(arr3.get(0).toString().length());
int l = arr3.get(0).toString().length();
int arr10[][] = new int[(l/2)][2];
for(int i=0;i< 2;i++)
{
for(int row = 0; row < (l/2);row++)
{
for(int gh = 0;gh < l;gh++)
{
if(i%2==0)
{
indEven = cArr[gh];
System.out.println(indEven);
arr10[row][i] = indEven;
//System.out.println(arr10[row][i]);
//row++;
}
else
{
indOdd = cArr[gh+1];
System.out.println(indOdd);
arr10[row][i] = indOdd;
//row++;
}
}
}
//arr10 = new int[indOdd][indEven];
//System.out.println(arr10);
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
infile.close();
}
}
But I'm stuck how to set one into the two dimensional array if the relation is {(a,b),(a,c),(b,a),(b,c),(c,c)}; and {(33,33),(45,45),(67,67),(77,77),(78,78)};
So, you have two problems: parsing the input and setting the array.
To parse the input, think about the format you're given. An opening curly brace, a bunch of ordered pairs, then a closing brace. Think about this pseudocode:
Read in a left curly brace
While the next character is not a right curly brace{
Read in a left parenthesis
Get the first number and put it in a variable!
Read in a comma
Get the second number and put it in a variable!
Read in a right parenthesis
Store your relation in the array!
}
Now your issue is just how to put it in the array. Your relations are practically already indexes into the grid! Note the 0-indexing, so just subtract 1 from both, and set the resulting coordinate equal to 1.
array[first number-1][second number-1]=1;
Just a TIP:
If your set is for example {b,c,e} and want to have somewhere stored relation elemnt <-> index like b<==>0, c<==>1, e<==>2 you can store that elements in List and then use method indexOf().
I mean something like this
List<String> list=new ArrayList<String>();
list.add("b");
list.add("c");
list.add("e");
System.out.println(list.indexOf("c"));//return 1
System.out.println(list.indexOf("e"));//return 2
System.out.println(list.indexOf("b"));//return 0
Now you just have to figure out how to use it to create your array.

Categories

Resources