Trying to put random strings into a file - string

I am trying to insert random strings into a .txt file. My code is as follows:
import java.util.*;
import java.io.*;
class fileProcessing{
public static void main (String[] args) throws Exception{
letter();
}
public static void letter() throws Exception{
int count = 0;
PrintStream out = new PrintStream(new File("nums.txt"));
while (count < 7 ){
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122 - 97) + 1);
char a = (char)randomNum;
out.print(a);
count++;
}
}
}
I'm trying to put a row of 7 random letters in a .txt file about 400 or so times. My code allows me to put in only a row of 7 letters. I'm not sure how to get the other 399 lines in. Any help would be appreciated. Thanks!

Use a nested loop that contains the loop you have already written. What this does is, after you generate one word, do a new iteration, writing another word in your file.
import java.util.*
import java.io.*;
class FileProcessing
{
public static void main(String[] args) throws IOException
{
letters();
}
public static void letters() throws IOException
{
int count;
PrintStream out = new PrintStream(new File("nums.txt"));
/*Outer loop. When the loop on the inside finishes generating
*a word, this loop will iterate again.
*/
for(int i=0; i<400; ++i)
{
count=0;
/*your current while loop*/
while (count < 7)
{
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122-97)+1);
char a = (char) randomNum;
out.print(a);
count++;
}
//print new line so all words are in a separate line
out.println();
}
//close PrintStream
out.close();
}
}
Learn more on nested loops here: http://www.javawithus.com/tutorial/nested-loops

Related

Investigating random forloop in the text?

I am trying to set up a program that saves users input into a file and then it outputs what the user entered as the average. I am using exception handling to detect if the user inputs letter. However, when the user inputs a letter it goes into an infinite loop. I am not able to figure out the issue. Please ignore the bad java. I just want it to function before I fix up the bad java.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class W11dot1 {
public static void main(String[] args) throws IOException {
System.out.println("This program gets ten numbers from the user, then computes and displays the average.");
int numOf = 1;
double doMath = 0;
double[] numArray = new double[10];
do {
try{
for(int i = 0; i<10; i++){
Scanner input = new Scanner(System.in);
System.out.print("Enter Integer " + numOf + ": ");
double num = input.nextDouble();
numArray[i] = num;
numOf+=1;
}
}catch (InputMismatchException e){
System.out.println("Error: input must be an integer");
}
}while (numOf != 11);
File file = new File("Average.txt");
try {
PrintWriter output = new PrintWriter(file);
for(int y = 0; y<numArray.length; y++){
output.println(numArray[y]);
}
output.close();
} catch (IOException ex){
System.out.println("Error: with file");
}
Scanner input = new Scanner(file);
while (input.hasNext()){
double moreNums = input.nextDouble();
doMath += moreNums;
}
input.close();
double average = doMath/10;
System.out.printf("The average of the input values is %.2f", average);
System.out.println("\nGoodbye...");
}
}
Firstly you do not need nested loops while taking the input, the nested loops are causing the issue every time you enter a character.
Each time you enter a character and the scanner throws an exception and the inner for loop is restarted again. You can fix this by simply removing inner for loop (not really needed) and modifying numOf variable will help you achieve that, you can do something like this -
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class W11dot1 {
public static void main(String[] args) throws IOException {
System.out.println("This program gets ten numbers from the user, then computes and displays the average.");
double doMath = 0;
double[] numArray = new double[10];
int numOf = 0;
Scanner input = new Scanner(System.in);
do {
try {
System.out.printf("Enter Integer %d: ", (numOf+1));
double num = input.nextDouble();
numArray[numOf++] = num;
} catch (InputMismatchException e) {
System.out.println("Error: input must be an integer");
}
} while (numOf < 10);
input.close();
File file = new File("Average.txt");
try {
PrintWriter output = new PrintWriter(file);
for (int y = 0; y < numArray.length; y++) {
output.println(numArray[y]);
}
output.close();
} catch (IOException ex) {
System.out.println("Error: with file");
}
input = new Scanner(file);
while (input.hasNext()) {
double moreNums = input.nextDouble();
doMath += moreNums;
}
input.close();
double average = doMath / 10;
System.out.printf("The average of the input values is %.2f", average);
System.out.println("\nGoodbye...");
}
}
Also there are so many optimizations and cleaning that can made to the programs but as you said you will fix those.
Hope this helps!
You shouldn't declare your Scanner inside of your loop. As it stands now, you're initializing 10 different scanners and not closing any of them. It should be declared outside of your loop.
Your for nested inside of your do...while is also interesting. I don't think the inner for loop is necessary, because your do...while should already be taking care of the right bounds. If you do get rid of it, you would replace numArray[i] with numArray[numOf] (and start numOf at 0).

How to scramble a String

I'm trying to make an Anagram puzzle where I input a word (for example, fire) and it scrambles it randomly around for me (and it ends up like "rfie", "frei", etc...) Below is the basics of what I'm trying to do. All I need to know is how to scramble the string.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input word");
String Word = sc.nextLine();
//Program jumbles word here
System.out.println(Word);
//Jumbled word is printed one previous line
}
You could use the following algorithm:
public static void main(String[] args){
String myWord = "Hello";
StringBuilder jumbledWord = new StringBuilder();
jumbledWord.append(myWord);
Random rand = new Random();
for (int i = myWord.length(); i > 0; i--)
{
int index1 = (rand.nextInt(i+1) % myWord.length());
int index2 = (rand.nextInt(i) % myWord.length());
char temp = jumbledWord.charAt(index1);
jumbledWord.setCharAt(index1, jumbledWord.charAt(index2));
jumbledWord.setCharAt(index2, temp);
}
System.out.println(jumbledWord);
}

using ANTLR in java cause OOM

I'm trying to parse a big log(30MByte) file with ANTLR.
But it crashed with OOM or became very slow as parser working.
As i knew,
1. Lexer scans text and yeids tokens
2. Parser consume tokens with given rule
Tokens already consumed should be collected by gc, but it seems not.
Can you tell me what is the problem?
(grammar or code)
Minimized grammars and codes are below
LogParser.g
grammar LogParser;
options {
language = Java;
}
rule returns [Line result]
:
stamp WS text NL
{
result = new Line();
result.setStamp(Integer.parseInt($stamp.text));
result.setText($text.text + $NL.text);
}
;
stamp
:
DIGIT+
;
text
:
CHAR+
;
DIGIT
:
'0'..'9'
;
CHAR
:
'A'..'Z'
;
WS
:
' '
;
NL
:
'\r'? '\n'
;
Test.java
import java.io.IOException;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
public class Test {
public static void main(String[] args) {
try {
CharStream input = new ANTLRFileStream("aaa.txt");
LogParserLexer lexer = new LogParserLexer(input);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
LogParserParser parser = new LogParserParser(tokenStream);
int count = 0;
while (true) {
count++;
parser.rule();
parser.setBacktrackingLevel(0);
if (0 == count % 1000)
System.out.println(count);
}
} catch (IOException e) {
e.printStackTrace();
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
Line.java
public class Line {
private Integer stamp;
private String text;
public Integer getStamp() {
return stamp;
}
public void setStamp(Integer stamp) {
this.stamp = stamp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public String toString() {
return String.format("%010d %s", stamp, text);
}
}
aaa.txt, randomly generated contents. its size is about 30mega byte.
0925489881 BIWRSAZLQTOGJUAVTRWV
0182726517 WWVNRKGGXPKPYBDIVUII
1188747525 NZONXSYIWHMMOLTVPKVC
1605284429 RRLYHBBQKLFDLTRHWCTK
1842597100 UFQNIADNPHQYTEEJDKQN
0338698771 PLFZMKAGLGWTHZXNNZEU
1971850686 TDGYOCGOMNZUFNGOXLPM
1686341878 NTYUXJSVQYXTBZAFLJJD
0849759139 YRXZSVWSZDBJPSNSWNJH
:
:
:
Sample generator
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class EntryPoint {
/**
* #param args
*/
public static void main(String[] args) {
FileWriter fw = null;
try {
int size = 20;
String formatLength = Integer.toString(Integer.MAX_VALUE);
String pattern = "%0" + formatLength.length() + "d ";
Random random = new Random();
File file = new File("aaa.txt");
fw = new FileWriter(file);
while (true) {
int nextInt = random.nextInt(Integer.MAX_VALUE);
StringBuilder sb = new StringBuilder();
sb.append(String.format(pattern, nextInt));
for (int i = 0; i < size; i++) {
sb.append((char) ('A' + random.nextInt(26)));
}
fw.append(sb);
fw.append(System.getProperty("line.separator"));
if (file.length() > 30000000)
break;
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result with JavaSE-1.6(jre6), windows 7 64 vmarg "-Xmx256M"
85000
86000
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at org.antlr.runtime.Lexer.emit(Lexer.java:160)
at org.antlr.runtime.Lexer.nextToken(Lexer.java:91)
at org.antlr.runtime.BufferedTokenStream.fetch(BufferedTokenStream.java:133)
at org.antlr.runtime.BufferedTokenStream.sync(BufferedTokenStream.java:127)
at org.antlr.runtime.CommonTokenStream.consume(CommonTokenStream.java:67)
at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:106)
at LogParserParser.text(LogParserParser.java:190)
at LogParserParser.rule(LogParserParser.java:65)
at Test.main(Test.java:21)
I believe UnbufferedTokenStream is what you want. Might need to unbuffer the char stream too.

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

Continuously add digits to a string

Just a quick one, I want to continuously add digits to a string. The first thing I did is to remove the last character of the string, now digits starting from 1 should be continuously added to it. The snippet is below:
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
class Class1
{
public static String source = "#box1";
static string dest;
public static void Main(String[] args)
{
try
{
if (source.Length > 0)
{
dest = source.Substring(0, source.Trim().Length - 1);
}
Console.WriteLine(dest);
Console.ReadLine();
}
catch(Exception e){ e.ToString(); }
}
}
}
The output should look like this:
#box1
#box2
#box3
#box4
#box5
and so on.....
If you have a max :
for (int i = 1; i <= max; i++)
{
Console.WriteLine("#Box" + i);
}
With no maximum, but that is not a good idea:
count = 1
while (1 > 0)
{
Console.WriteLine("#Box" + count);
count++;
}
You can also do no max with the for loop, but I just wanted to give you more options in loops.
Information on loops http://csharp.net-tutorials.com/basics/loops/
Thanks, guys,
I got it solved this way. Sorry that I have to post the real code I'm using it for. I'm much occupied than to edit the pseudo code again.
public static String RegistrationFailedPanels = UserValidations.RegistrationFailedPanels;
public static String CloseFailedPanel = UserValidations.CloseFailedPanel;
static int count = 0;
public void LoginFailed(String InputConstant, String FailedLogin)
{
++count;
InputConstant = RegistrationFailedPanels.Substring(0, RegistrationFailedPanels.Trim().Length-1);
FailedLogin = CloseFailedPanel.Substring(0, CloseFailedPanel.Trim().Length-1);
new LoginValidations(driver).WaitForATime(InputConstant +count);
driver.FindElement(By.CssSelector(FailedLogin +count)).Click();
}

Resources