While writing a project for a non CS class I ran into a problem. The project i had in mind is a type of quiz, wherein the user is asked a question and is given multiple choices for answers. Now, I intended to type these questions into a .txt file and use a file scanner to read them in, and create an array of questions like so:
public static String[] questionToString(Scanner sf) {
String temp = "";
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp += sf.nextLine();
}
questions[i] = temp;
i++;
temp = "";
return questions;
}
However, this code when tested would return something along the lines of:
Question 1 abcd
as opposed to:
Question 1
a
b
c
d
I want each character to be placed on it's own line, like in the second example. How can I do this while printing the strings? (System.out.println())
Eventually, I plan to put them on a DrawingPanel with the questions lined up below.
Thanks!
Use "\n" to add an extra line in addition to the line println() already appends:
System.out.println(your_var + "\n")
That is because you are adding questions lines to a string. So make a small change to the following line:
temp += sf.nextLine() + "\n";
Of course, the newline char depends on which environment you are running (\n or \r\n).
Best way to append many strings into one with a new line character after each one is to use StringBuilder. I have rewritten your code using StringBuilder
public static String[] questionToString(Scanner sf) {
StringBuilder temp = new StringBuilder();
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp.append(sf.nextLine());
temp.append(System.lineSeparator());
}
questions[i] = temp.toString();
i++;
temp = new StringBuilder();
return questions;
}
NOTE: Please don't append /n with your string as the new line character differs for different operating system. I will advise you to use System.lineSeparator(), this will append the new line character depending on the operating system you are running you code on.
Related
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 2 years ago.
Improve this question
Very new java student here (My first post, sorry for wrong formatting). I need help with rephrasing a paragraph.
I need to change the letters of the paragraph to the 13th next letter ie changing a to n and so on meanwhile conserving the structure of the paragraph ie line breaks, full stops, etc...I have only been able to change a word so far and need to expand this code to be able to do it with a paragraph...Thanks in advance...Much appreciated...
public class Assignment1b {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please type any word: ");
String word = s.nextLine();
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
System.out.println("The encrypted word is: " + ROT13);
}
}
General good programming practice: one method does one thing, and one thing only. This makes code easier to read, test, maintain and reuse. I suggest you start by taking the stuff in your for () loop and sticking it in a new method. Call it private char encryptCharacter(char oldCharacter), or some such. Add the return value to your ROT13 string to build the answer, as you are currently doing.
Your problem is now in this secondary module - how to preserve line breaks, spaces and similar characters. Refer to Charlie Armstrong's comment, that will help you identify them. You will probably end up with something like:
private char encryptCharacter(char oldCharacter) {
if (isWhiteSpaceOrPunctuation(oldCharacter)) {
return oldCharacter;
} else {
// add your code to encrypt the character here
return encryptedCharacter;
}
}
private boolean isWhiteSpaceOrPunctuation(char character) {
// return true or false, as appropriate
}
First you need to split paragraph by words, using method split of String class and passing the char, that splits words, in this case, the space " ". This method return array of String (String[]), which means, array of words, but I convert it to List<String> using Arrays.asList() method, to facilitate the process. Next, I iterate this list, and apply the rephrase method, that encript or change each word.
// this split your paragraph, and invoke your code, which means, rephrase method by word
public static String encript(String paragraph){
// split words by spaces, but punctuation still
List<String> words = Arrays.asList(paragraph.split(" ").clone());
StringBuilder sb = new StringBuilder();
for(String word : words) {
// rephrase and append
sb.append(rephrase(word));
}
return sb.toString();
}
// this is your code in a method, I recommend you rebuild this method using StringBuilder, it is more efficient
public static String rephrase(String word){
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
return ROT13;
}
I currently have a program that stores objects in an array that I need to store in an ArrayList instead.
This is how the objects were originally stored.
private String phrase = "Once upon a time";
private Letter[] letter_array = new Letter[16];
for (int i = 0; i < phrase.length(); i++) {
letter_array[i] = new Letter(phrase.charAt(i));
}
So now, I'm trying to use something like this instead.
private String phrase = "Once upon a time";
ArrayList<Letter> aToZ = new ArrayList<Letter>();
for (int i = 0; i < phrase.length(); i++) {
Letter x = new Letter.charAt(i);
aToZ.add(x);
}
Some of the code has been omitted, but these are the pertinent parts.
This doesn't work and I've tried variations, but I just really don't know how to do this.
Instead of
Letter x = new Letter.charAt(i);
you need
Letter x = new Letter(phrase.charAt(i));
in your 2nd code snippet
Letter x = new Letter(phrase.charAt(i));
You almost had it! You need to include the "phrase." before charAt, but everything else seems to be correct.
Try to think of the object > string > charAt sequence carefully when you reread your code. Ask yourself when you read over your code: "what is it exactly about the object that I want to reference/change?"
Say you have a text file with "abcdefghijklmnop" and you have to add 3 characters at a time to an array list of type string. So the first cell of the array list would have "abc", the second would have "def" and so on until all the characters are inputted.
public ArrayList<String> returnArray()throws FileNotFoundException
{
int i = 0
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
while (scanCharacters.hasNext())
{
list.add(scanCharacters.next().substring(i,i+3);
i+= 3;
}
scanCharacters.close();
return characters;
}
Please use the below code,
ArrayList<String> list = new ArrayList<String>();
int i = 0;
int x = 0;
Scanner scanCharacters = new Scanner(file);
scanCharacters.useDelimiter(System.getProperty("line.separator"));
String finalString = "";
while (scanCharacters.hasNext()) {
String[] tokens = scanCharacters.next().split("\t");
for (String str : tokens) {
finalString = StringUtils.deleteWhitespace(str);
for (i = 0; i < finalString.length(); i = i + 3) {
x = i + 3;
if (x < finalString.length()) {
list.add(finalString.substring(i, i + 3));
} else {
list.add(finalString.substring(i, finalString.length()));
}
}
}
}
System.out.println("list" + list);
Here i have used StringUtils.deleteWhitespace(str) of Apache String Utils to delete the blank space from the file tokens.and the if condition inside for loop to check the substring for three char is available in the string if its not then whatever character are left it will go to the list.My text file contains the below strings
asdfcshgfser ajsnsdxs in first line and in second line
sasdsd fghfdgfd
after executing the program result are as,
list[asd, fcs, hgf, ser, ajs, nsd, xs, sas, dsd, fgh, fdg, fd]
public ArrayList<String> returnArray()throws FileNotFoundException
{
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
String temp = "";
while (scanCharacters.hasNext())
{
temp+=scanCharacters.next();
}
while(temp.length() > 2){
list.add(temp.substring(0,3));
temp = temp.substring(3);
}
if(temp.length()>0){
list.add(temp);
}
scanCharacters.close();
return list;
}
In this example I read in all of the data from the file, and then parse it in groups of three. Scanner can never backtrack so using next will leave out some of the data the way you're using it. You are going to get groups of words (which are separated by spaces, Java's default delimiter) and then sub-stringing the first 3 letters off.
IE:
ALEXCY WOWZAMAN
Would give you:
ALE and WOW
The way my example works is it gets all of the letters in one string and continuously sub strings off letters of three until there are no more, and finally, it adds the remainders. Like the others have said, it would be good to read up on a different data parser such as BufferedReader. In addition, I suggest you research substrings and Scanner if you want to continue to use your current method.
I am trying to take a file full of strings, read it, then print out a few things:
The string
The string backwards AND uppercase
The string length
There are a few more things, however I haven't even gotten to that point and do not want to ask anyone to write the code entirely for me. After messing around with it for a while, I have it almost completed (I believe, save for a few areas).
The piece that is tripping me up is the backwards word. We are required to put our output neatly into columns using prinf, but I cannot do this if I read each char at a time. So I tried setting a String backwardsWord = ""; and adding each character.
This is the piece that is tripping me up:
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
backwardsWord += (upperCaseWord.charAt(i) + "");
}
My issue is that when I print it, the first word works properly. However, each word after that is added to the previous word.
For example: if I am printing cat, dog, and rat backwards, it shows
TAC
TACGOD
TACGODTAR
I obviously want it to read
TAC
GOD
TAR
Any help would be appreciated.
It looks like your variable backwardsWord is always appending a character without being reset between words. The simplest fix is to clear the backwardsWord just before your loop by setting it to empty string.
backwardsWord = ""; //Clear any existing characters from backwardsWord
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
backwardsWord += (upperCaseWord.charAt(i) + "");
}
If you are building up a String one character at a time you will be using a lot of memory because Java Strings are immutable.
To do this more efficiently use a StringBuilder instead. This is made for building up characters like what you are doing. Once you have finished you can use the toString method to get the String out.
StringBuilder builder = new StringBuilder(); //Creates the String builder for storing the characters
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
builder.append(upperCaseWord.charAt(i)); //Append the characters one at a time
}
backwardsWord = builder.toString(); //Store the finished string in your existing variable
This has the added benefit of resetting the backwardsWord each time.
Finally, since your goal is to get the String in reverse we can actually do it without a loop at all as shown in this answer
backwardsWord = new StringBuilder(upperCaseWord).reverse().toString()
This creates a new StringBuilder with the characters from upperCaseWord, reverses the characters then stores the final string in backwardsWord
Where are you declaring the String backwardsWord?
If you don't clear it between words then the memory space allocated to that string will still contain the previously added characters.
Make sure you are tossing in a backwardsWord = ""; in between words to reset it's value and that should fix your problem.
Without seeing more of your code I can't tell you exactly where to put it.
This should do the job ->
class ReverseWordsInString{
public static String reverse(String s1){
int l = s1.length();
if (l>1)
return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
else
return(s1.substring(0));
}
public static void main(String[] args){
String st = "Cat Dog Rat";
String r = "";
for (String word : st.split(" "))
r += " "+ reverse(word.toUpperCase());
System.out.println("Reversed words in the given string: "+r.trim());
}
}
Hey guys, I'm new to Java (well, 3/4 of a year spent on it).
So I don't know much about it, I can do basic things, but the advanced concepts have not been explained to me, and there is so much to learn! So please go a little but easy on me...
Ok, so I have this project where I need to read lines of text from a file into an array but only those which meet specific conditions. Now, I read the lines into the array, and then skip out on all of those which don't meet the criteria. I use a for loop for this. This is fine, but then when I print out my array (required) null values crop up all over the place where I skipped out on the words.
How would I remove the null elements specifically? I have tried looking everywhere, but the explanations have gone way over my head!
Here is the code that I have to deal with the arrays specifically: (scanf is the scanner, created a few lines ago):
//create string array and re-open file
scanf = new Scanner(new File ("3letterWords.txt"));//re-open file
String words [] = new String [countLines];//word array
String read = "";//to read file
int consonant=0;//count consonants
int vowel=0;//count vowels
//scan words into array
for (int i=0; i<countLines; i++)
{
read=scanf.nextLine();
if (read.length()!=0)//skip blank lines
{
//add vowels
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
{
if (read.charAt(2)=='a'||read.charAt(2)=='e'||read.charAt(2)=='i'||read.charAt(2)=='o'||read.charAt(2)=='u')
{
words[i]=read;
vowel++;
}
}
//add consonants
if (read.charAt(0)!='a'&&read.charAt(0)!='e'&&read.charAt(0)!='i'&&read.charAt(0)!='o'&&read.charAt(0)!='u')
{
if (read.charAt(2)!='a'&&read.charAt(2)!='e'&&read.charAt(2)!='i'&&read.charAt(2)!='o'&&read.charAt(2)!='u')
{
words[i]=read;
consonant++;
}
}
}//end if
//break out of loop when reached EOF
if (scanf.hasNext()==false)
break;
}//end for
//print data
System.out.println("There are "+vowel+" vowel words\nThere are "+consonant+" consonant words\nList of words: ");
for (int i=0; i<words.length; i++)
System.out.println(words[i]);
Thanks so much for any help received!
Just have a different counter for the words array and increment it only when you add a word:
int count = 0;
for (int i=0; i<countLines; i++) {
...
// in place of: words[i] = read;
words[count++] = read;
...
}
When printing the words, just loop from 0 to count.
Also, here's a simpler way of checking for a vowel/consonant. Instead of:
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
you can do:
if ("aeiou".indexOf(read.charAt(0)) > -1)
Update: Say read.charAt(0) is some character x. The above line says look for that character in the string "aeiou". indexOf returns the position of the character if found or -1 otherwise. So anything > -1 means that x was one of the characters in "aeiou", in other words, x is a vowel.
public static String[] removeElements(String[] allElements) {
String[] _localAllElements = new String[allElements.length];
for(int i = 0; i < allElements.length; i++)
if(allElements[i] != null)
_localAllElements[i] = allElements[i];
return _localAllElements;
}