I am trying to write a program in Java so I can read a file, reverse every single word, meaning if the sentence is "Hello Java" the output should be "olleH avaJ".I have been able to do the reverse but with the program I have written the output is "olleHavaJ" with no space. Can someone help me fix it? Thank you!
import java.util.Scanner;
import java.io.*;
public class ReadWords {
public static void main(String[] args) throws FileNotFoundException {
File f=new File("words.txt");
Scanner input=new Scanner(f);
String result="";
while(input.hasNextLine()) {
String fjala=input.next();
for(int i=fjala.length()-1;i>=0;i--) {
result+=fjala.charAt(i);
}
}
input.close();
System.out.print(result+" ");
}
}
Making my initial comment as an answer.
You can add a space once you have constructed the reversed word.
for(int i=fjala.length()-1;i>=0;i--) {
result+=fjala.charAt(i);
}
result += " ";
You can use nextLine() instead of next( ) (though this can be solved using next also) method, and do split(" ") and assign it in String[ ] as follows.
String[ ] words = in.nextLine( ).trim( ).split(" ");
Now apply reverse function on each word and push it in the output file.
Hope this solves your problem :)
Related
I'm learning to code Java with mooc at the moment and am doing an assignment where you take user input (and do stuff with it). The program/loop ends if user inputs nothing and enters.
So this is the right answer which I did correctly:
while (true) {
String sentence = scanner.nextLine();
if (sentence.equals("")) {
break;
}
}
However before this I also tried something like:
while (!scanner.nextLine().equals("")) { // ...
Why does that method not work? I don't see anything wrong with it.
(Below is the whole code if needed)
import java.util.Scanner;
public class AVClub {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (!scanner.nextLine().equals("")) {
String sentence = scanner.nextLine();
String[] array = splitter(sentence);
for (int i = 0; i < array.length; i++) {
if (array[i].contains("av")) {
System.out.println(array[i]);
}
}
}
}
public static String[] splitter(String sentence) {
String[] array = sentence.split(" ");
return array;
}
}
Try using scanner.hasNext() to see if there is anything else that you can read in. Instead of your splitter method, you can use StringTokenizer which will tokenize the String by spaces.
The reason your code does not work is because you are calling Scanner.nextLine() twice. Even though your code:
while (!scanner.nextLine().equals(""))
is a condition check, it reads it in and moves on. Think about it like this: The Scanner is like a book reader. When you call Scanner.nextLine(), the book reader moves to that line and reads it. When you called it again, it read an empty line. For example, if I input this:
Your reader will read in the "I like pie" and check to see that it is not a "". When it is done, and you get your sentence variable, you called the method again, which reads in the NEXT line, which is not there. So your code fails to work.
As my class project I have written some codes that receives a sentence and if it has a special character by checking it's ASCII code it replaces it with another one. But unfortunately every time it replaces and shows only first word and deletes rest of the sentence. Please help me and if there's a better way for this it's appreciated.
here's my code:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
if (s.contains("\u0626")) {
String result = s.replaceAll("\u0626", "\u0628");
System.out.println(result);
}
}
}
I am trying to take a user entered word or phrase and put the characters in alphabetical order by putting them in a list and sorting the list. Here is my code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SortAlphabetically {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Character> alpha = new ArrayList<Character>();
System.out.println("Enter a word or phrase");
StringBuilder input = new StringBuilder(scanner.next());
scanner.close();
for (int i = 0; i < input.length(); i++) {
if (Character.isWhitespace(input.charAt(i))) {
input.deleteCharAt(i);
} else {
alpha.add(input.charAt(i));
}
}
alpha.sort(null);
System.out.println("Input sorted alphabetically: " + alpha);
}
}
However, the input seems to stop being entered into the list after a white space character. For example:
Enter a word or phrase
cba fed
Input sorted alphabetically: [a, b, c]
I tried to fix this with
if (Character.isWhitespace(input.charAt(i))) {
input.deleteCharAt(i);
}
but it doesn't seem to have done anything
scanner.next() reads a single token, so it stops at the first white space.
If you use scanner.nextLine(), it will read the entire line, including the space.
You have to use the scanner.nextLine() to get the entire line with all the white-spaces. In addition, you have a better way to implement the solution in just one line using simple java library functions in java.lang.String. Why waste lines!
System.out.println("Answer"+input.replaceAll( " ", "" ).toCharArray().toList().sort());
Can any one tell me that how to use Scanner Class of Java to find the frequency of a word in a sentence.
I am confused as to enter a line in java i have to use nextInt() function but to compare need it to convert in char so how to do so.
For example:-
I enter on terminal window(Giving Input)
This is my cat.
Now i have to find the FREGUENCY of word "this" in the above sentence. Please can you give me some idea.REMEMBER THE RESTRICTION IMPOSED ON IT IS I HAVE TO USE ONLY SCANNER CLASS OF JAVA LIBRARY
PROGRAMME USING STREAM READER IS AS FOLLOWS-
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
alternative solution using pattern
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
try out this.
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
int count = 0;
while (!sentence.equals("")){
if(sentence.contains(word)){ // check if the word is in the sentence; if yes cut the sentence at the index of the first appearance of the word plus word length
// then check the rest of the sentence for more appearances
sentence = sentence.substring(sentence.indexOf(word)+word.length());
count++;
}
else{
sentence = "";
}
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
You can enter a String too using Scanner Class . Here is your code that i modified , and it working . `
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String: ");
String s=in.nextLine();
System.out.println("Enter substring: ");
String sub=in.nextLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
The nextLine() method of Scanner class let you input Strings.
Don't listen to #Uzochi. His answers may work, but they're way too complicated and may actually slow your program down.
For the Scanner class, there are multiple ways of reading in numbers or text:
nextInt() - scans in the next integer value
nextDouble() - scans in the next double value
nextLine() - scans in the next line of text
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html - scroll down to method summary, and in the middle of all of the methods, you will find all of the "next" methods.
Note that there is a small bug with Scanner (at least with the last time I used it). Say you're using a Scanner called scan. If you call
scan.nextInt();
scan.nextLine();
(which reads in an integer and then a line of text), your Scanner will skip the call to nextLine(). This is a small bug that can easily be fixed by adding another nextLine(). It will catch the second nextLine.
In response to #Uzochi, there is a much simpler solution to your algorithm. Your algorithm is actually faster than his, although there are some small things that could make your program run a tiny bit faster:
1) Use a while loop instead of a for loop. Your use of indexOf() makes the current index of the String s you're at skip forward a lot, so there's virtually no point in having a for loop. You can easily change it into a while loop. Your conditions would be to keep checking if indexOf() returns a non-negative value (-1 means there is no value), and you increment that index value by 1 (like the for loop does automatically).
2) Smaller thing - you don't need the line:
ind=-1;
Your current code will always modify ind before it hits that if statement, so there is virtually no reason to have this line in the program.
EDIT - #Uzochi may be using Java's built in libraries, but for a beginner like OP, you should be learning how to use for and while loops to efficiently write code.
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks