Word Anagram not getting all user input - java

I am writing a program checking if n words are anagrams of the initially given word. It the word is an anagram it prints "yes", if it isn't - prints "no". It solves the problem correctly if I input all the data manually in the console. If I copy and paste the data it does not "see" the last line until I hit enter again. So it I paste the following input:
anagram
6
gramana
aaagrnm
anagra
margana
abc
xy
So I get only 5 yes-es and no-s and when I hit enter again I get the last no.
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class WordAnagrams {
public static void anagramCheck (String x, String y) {
char[] initial= new char[x.length()];
for (int i=0; i<x.length(); i++) {
initial[i]=x.charAt(i);
}
Arrays.sort(initial);
char[] isAnagram = new char[y.length()];
for (int i=0; i<y.length(); i++) {
isAnagram[i]=y.charAt(i);
// System.out.println(isAnagram[i]);
}
Arrays.sort(isAnagram);
boolean same=Arrays.equals(initial, isAnagram);
if (same) {
System.out.println ("yes");
}
else {
System.out.println ("no");
}
// return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String word = input.nextLine();
int n = Integer.parseInt(input.nextLine());
String anagram=""; // input.nextLine();
// int counter=0;
System.out.println();
/* while (counter<n+1) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
counter++;
}*/
for (int i=0; i<=n; i++) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
// System.out.println(answers[i]);
}
System.out.println();
}
}

The issue is that when you copy paste the input, the last word have no '\n' at the end so the scanner doesn't read this as a line until you press ENTER.
So what I can propose is:
1) Use a File for an Input
Or 2) Use InputStreamReader to fetch from the console. Here is some code to do it:
`
public static void main(String[] args) throws IOException {
char buffer[] = new char[512];
InputStreamReader input = new InputStreamReader(System.in);
input.read(buffer,0,512);
String data[] = (new String(buffer)).split("\n");
}
`
It give you a list of strings at the end. PS: Your loop "for(int i =0;i<=n;i++)" is looping 7 times with n = 6.

#kalina199
You could also shorten your code a bit to save yourself from defining a method to check the input from the console.
I did it by splitting the console input into a String array using a simple regex and immediately sorted it.
Then my loop does a simple check to compare the new user input to the original word by their lengths and if that doesn't match you just print out "no" and continue with the next word.
Here's my code:
package bg.Cholakov;
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] initWord = scanner.nextLine().split("");
Arrays.sort(initWord);
int num = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < num; i++) {
String[] testWord = scanner.nextLine().split("");
Arrays.sort(testWord);
if (!(initWord.length == testWord.length)) {
System.out.println("no");
} else if (initWord[i].equals(testWord[i])) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}

Related

Java program of returning alphabets that a word is made of

I am trying to understand how pieces of code are contributing the program in java. So the program is supposed to take input from user for a word and then the output is printing the alphabets that the user inputted word is made of. The program is running fine but I need help in interpreting what the for loops are doing. Thank you!
import java.util.Scanner;
public class J0307_search {
public static void main(String[] args) {
String str1;
int count;
char[] arr1=new char[40];
Scanner s=new Scanner (System.in);
System.out.print("input a string:");
str1=s.nextLine();
arr1[0]=str1.charAt(0);
System.out.print(arr1[0]+"");
for (int i=1; i<str1.length();i++) {
count=0;
for (int j=0;j<i;j++) {
if (str1.charAt(i)==str1.charAt(j)) {
count++;
}
}
if (count<1) {
arr1[i]=str1.charAt(i);
System.out.print(arr1[i]+"");
}
}
System.out.print(" : only made up of these alphabets");
s.close();
}
}
I change code and add explain.
boolean behindExist;
for (int i=1; i<str1.length(); i++) {//loop for all character in string
behindExist = false;
for (int j=0; j < i; j++) {
//check same character is exist before now char
//Ex) if (i = 3), check
//str1.charAt(3) == str1.charAt(0);
//str1.charAt(3) == str1.charAt(1);
//str1.charAt(3) == str1.charAt(2);
if (str1.charAt(i)==str1.charAt(j)) {
behindExist = true;
}
}
if (!behindExist) {//if not behindExist
arr1[i]=str1.charAt(i);//add to arr1
System.out.print(arr1[i]+"");//and print character
}
}
And, this is my code.
Scanner sc = new Scanner(System.in);
System.out.print("input a string : ");
String input = sc.nextLine();
for(int charCode : input.chars().distinct().toArray()) {
System.out.print((char)charCode);
}
System.out.print(" : only made up of these alphabets");
sc.close();
Short. I love it. I hope this can be help. :)
Can we use something as simple as this? The Set will contain unique characters that make up the word.
char[] charArr = str1.toCharArray();
Set<Character> charSet = new HashSet();
for(char c: charArr){
charSet.add(c);
}
Why to complex the problem.
Try to use features of collection in java.
something like this:-
Set<Character> set = new HashSet(Arrays.asList(str1.toCharArray()));

Palindrome Checker with nested loops thats checks the input and then flips its to compare

Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}

counting the alphabets from input

I need to write a code in java, which will take the input as a string from the user and will print the count of repetition of each alphabet. I Ihave written the code but not got the correct output.
input:ppooj
output:p1,o2,j1
My code is:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i]==arr[k])
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}
You can follow these steps.
Read input.
split the input to characters. (You can get the char[] from String)
Iterate the char[] and you can use Map<Character,Integer> to store character vs number of occurrences.
Now your map contains all characters with occurrences.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class AlphaCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String str = sc.nextLine();
Map<Character, Integer> map = new HashMap<Character, Integer>();
char[] chArray = str.toCharArray();
for(char c : chArray){
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}
else{
map.put(c, 1);
}
}
for (Entry<Character, Integer> entry : map.entrySet())
{
System.out.print(entry.getKey() + "" + entry.getValue()+" ");
}
}
}
If you use only alphabets, try this approach
Take an array of size 26
Assign array with 0
let the index be the alphabet position like 0-a, 1-b ... 25-z
oop through the input string and increment the respective index position like
array[inputString.charAt(i)-'a']++;
Print the result accordingly
Use equals method to compare reference objects value. As sometimes it get struck in the heap. So, it is better to use equals method over "==" while comparing values of reference objects.
Array is a reference type object.
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
// System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
// System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i].equals(arr[k]))
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}
Try this code. You can modify it as per your requirement in the application.
You can try Map with String as the key like this:
Map<String,Integer> map = new HashMap<String,Integer>();
// set value = 0 to characters from a-z.
for( int i = 'a'; i < 'z'; i++ ){
map.put(String.valueOf((char)i), 0);
}
// supposed you have this as your input array. This should be read from file.
String[] arr= {"p","p","o","o","j"};
// count the duplicated characters.
for(int i=0;i<arr.length;i++){
map.put(arr[i],map.get (arr[i])+1);
}
// remove duplicated characters in array.
List<String> list= new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(arr)));
// print result.
for (String string : list) {
System.out.print(string+map.get(string));
}

Trying to Convert a string to another string from array in a file on only the first space

Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}

Java Word Counter -- Write method that accepts string object as argument and returns word count

The assignment for java is to write a method that accepts string objects as an argument and returns the number of words it contains. Demonstrate the method in a program that asks the user to input a string and passes it to the method. The number of words should be displayed in the screen.. I know its close but there are probably some errors.
public class WordCounter
{
public static void main(String[] args)
{
//Imported scanner here
Scanner in = new Scanner(System.in);
//
//Asks and gets the users input here
//
private static string getInput(Scanner in)
{
String input;
System.out.println("Enter a string here: ");
input = in.nextLine();
//
//Create an if/else statment to find out if the user entered input.
//
if(input.length() > 0)
{
getInput(input);
}
else
{
System.out.println("Error -- You must enter a string!");
System.out.println("Enter a string here: ");
input = in.nextLine();
}
return input;
} //Close public static string getInput here
//
//Calculates the number of words the user inputs
//
public static int getWordCount(String input)
{
int wordcount = 0; //Initializes word counter to 0 at start of program
for(int i = 0; i <= input.length() -1; i++)
{
if(input.charAt(i) == ' ')
{
wordcount++;
}
}
return wordcount;
} //Close public static int getWordCount here
//Print out the number of words within the users string here
System.out.println("The number of words in the string are: " + wordcount);
} //Close public static void main string args here
} //Close public class word counter here
Try this smple method to find wordCount,
public int getWordCount(String value)
{
String[] result = value.split(" ");
return result.length;
}
you wrote all the methods in your main method it wont compile. Place it out side and then try.
Corrections:
You need to call getWordCount if there are any characters in the
input string
if(input.length() > 0)
{
getInput(input); // getWordCount(input);
}
If you just want to count the number of words in the string, do this
int counter = 0;
for(int i = 0; i <= input.length() -1; i++) {
counter++;
}
If you want to avoid counting spaces put, the condition and do continue.

Categories