I am trying to print user inputs in another class in Java. I have made a chessboard which asks the user to input strings on the board, and then, when these strings are printed on screen, I would like the output to be "You have placed piece [name] at coordinate [coordinate]". I am trying to do this in another class rather in the main method, but what I have tried so far doesn't seem to work. Here's my code.
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++);
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
So what I'd like to do is have a new class that uses that last print line to instead print the desired output that I mentioned earlier. Any help would be appreciated, thanks!
EDIT:
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard1
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
System.out.println(Arrays.deepToString(grid));
}
}
}
}
I have 2 separate files userInputs and showInput but they it says that they should still be declared in a separate file?
It's wrong to write main Function in every class, the program uses the main function to start from it, So you should write it only in the main project class and call inside it the other classes.
Your code should be:
package com.company;
public class ChessBoard
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
and other classes in separate files like:
package com.company;
import java.util.Scanner;
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
and another class to output:
package com.company;
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
//Print Your Data
}
}
}
}
Like #Atef Magdy said, You should have one class which holds all the data and functions
and a main class which executes the functions.
and the explanation for this error ( it states that using public int is an "illegal start" to the expression, and that it needs a ";" after it?) I have seen that you made the 2d Array of Type String?
String[] [] grid = new String [8][8];
and then returning it as a 1D Array of Type int?
public int[] getGrid(){
return grid.clone();
}
I should say that this is the source of this error. You should change the 'int[]' to 'string[][]'
if there is any error please reply to this answer!
Related
What I mean to say is, if I have an array which is delimited by spaces how can I distinguish if two consecutive chars are two or more digit numbers instead?
Bear with me I'm still pretty new to programming in general.
this is what I have so far:
import java.util.*;
public class calc
{
public static String itemList;
public static String str;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
delimitThis();
sc.close();
}
public static void delimitThis()// Delimiter to treat variable and numbers as seperate
{
List<String> items = Arrays.asList(str.split("\\s+"));
System.out.println(items);
for (int i = 0; i < str.length(); i++)
{
itemList = items.get(i);
category();
}
}
public static void category()////For Filtering between vars and constants and functions
{
for (int x = 0; x < itemList.length(); x++)
{
char ite = itemList.charAt(x);
if(Character.isDigit(ite))
{
System.out.println(ite + "is numeric"); //Will be replaced by setting of value in a 2 dimensional list
}
}
}
First of all, I want to fix your mistakes:
Mistake 1:
// bad
for (int i = 0; i < str.length(); i++)
{
itemList = items.get(i);
category();
}
You are traversing through List<String> items, but str.length is being used. It is wrong. To {print the item then do category()} for every item in items, the code should be:
// fixed
for (int i = 0; i < items.size(); i++)
{
itemList = items.get(i);
category();
}
Mistake 2:
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList);
}
I'm not sure what you wanted to do here. It's just that your code does not make sense to me. I assume you wanted to print line every character from itemList, the code should look like this:
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList.charAt(x));
}
Done with the mistakes. Now checking an a string whether it contains 2 digit numbers or more, we can use String.matches() with regular expression:
if(itemList.matches("\\d\\d+")){
System.out.println(itemList + " is a two or more digit number");
}else{
System.out.println(itemList + " is NOT a two or more digit number");
}
The code looks like this in the end:
import java.util.*;
public class Calc
{
public static String itemList;
public static String str;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
delimitThis();
sc.close();
}
public static void delimitThis()// Delimiter to treat variable and numbers as seperate
{
List<String> items = Arrays.asList(str.split("\\s+"));
System.out.println(items);
for (int i = 0; i < items.size(); i++)
{
itemList = items.get(i);
category();
}
}
public static void category()////For Filtering between vars and constants and functions
{
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList.charAt(x));
}
// is 2 digit number or not?
if(itemList.matches("\\d\\d+")){
System.out.println(itemList + " is a two or more digit number");
}else{
System.out.println(itemList + " is NOT a two or more digit number");
}
}
}
To check whether a string is at least a 2 digit number, use this regex: \d{2,}.
public static boolean is2OrMoreDigits(String s) {
Pattern p = Pattern.compile("\\d{2,}");
return o.matcher(s).matches();
}
So I have this code that takes in an array of names and sorts them alphabetically. I am wondering how to make it check to see if names entered are words (i.e. it has characters that are letters and not numbers or punctuation, etc.). An if not print out like "name entered is incorrect re run code" Thanks for help in advanced!
import java.util.Scanner;
public class Alphabetical_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Depending on your definition of "letters", one of the following will do:
private static boolean isAllEnglishLetters(String text) {
return text.matches("[a-zA-Z]+");
}
private static boolean isAllEnglishLetters(String text) {
return text.matches("\\p{Alpha}+"); // An alphabetic character: [a-zA-Z]
}
private static boolean isAllUnicodeLetters(String text) {
return text.matches("\\p{L}+"); // A unicode letter category
}
TEST
public static void main(String[] args) {
System.out.printf("%17s %s%n", "English", "Unicode");
test("John");
test("JohnDoe");
test("Schäfer");
test("John2");
test("John.Doe");
test("John Doe");
}
private static void test(String text) {
System.out.printf("%-10s %-5s %-5s%n", text, isAllEnglishLetters(text),
isAllUnicodeLetters(text));
}
OUTPUT
English Unicode
John true true
JohnDoe true true
Schäfer false true <-- Notice this
John2 false false
John.Doe false false
John Doe false false
Update
The code above shows a reusable method, which can simply be called where needed. You can of course just do the matches() call directly, e.g.
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
if (! names[i].matches("\\p{L}+"))
{
System.out.println("name entered is incorrect re run code");
return; // exit program
}
}
One option would be to replace all non word characters with nothing and check that the length of the resulting string is still the same length. Here is a one line method which accomplishes this:
private static boolean isAllEnglishLetters(String text) {
return name.replaceAll("[^a-zA-Z]", "").length() == name.length();
}
In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}
so I have this task where I must enter two strings and after that I have to find what are there common letters,and then write them out but only once..so for example
if the string1 is "onomatopoeia" and string2 is "conversation" I should get back:
o,n,a,t,e,i... My only problem is the last part("I don't know how to write the letters only once)
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class Zadatak4 {
/**
* #param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz2.length; j++) {
if (niz[i] == niz2[j]) {
System.out.println(niz[i] + " ");
// What now!?!?!?
}
}
}
}
}
Use a set:
LinkedHashSet<string> printNum = new LinkedHashSet<string>();
if(niz[i] == niz2[j])
{
printNum.add( niz[i] );
}
// outside of loop
for( string s : printNum )
{
System.out.println(s);
}
in the innermost section of your for loop you're going to want to add them to a set
mutuals.add(niz[i])
then outside the loop at the beginning add this to declare it
Set<char> mutuals = new HashSet<char>()
make sure you do this OUTSIDE the loop
then afterwards, print out everything in mutuals
You could do this by utilizing two HashSets.
You have one hashset per word. When you encounter a letter in word1 you enter in set1.
When you encounter letter in word2 you enter in set2.
Finally, you only keep the letters that are in both sets.
import java.util.HashSet;
public class Zadatak4 {
/**
* #param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
HashSet<Integer> set1 = new <String>HashSet();
HashSet<Integer> set2 = new <String>HashSet();
for(int i = 0; i < niz.length; i++)
{
if(!set1.contains(niz[i]));
set1.add((int) niz[i]);
}
for(int i = 0; i < niz2.length; i++)
{
if(!set2.contains(niz2[i]));
set2.add((int) niz2[i]);
}
Iterator<Integer> it = set1.iterator();
int currentChar;
while(it.hasNext())
{
currentChar = it.next();
if(set2.contains(currentChar))
System.out.println((char)currentChar);
}
}
}
What you need is an intersection of the two sets, so what you could use is Set.retainAll().
Almost everyone suggesting Set, here is the hard way of doing it...
public static void main(String[] args) {
String printed = "";
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
for(int i = 0; i < niz.length; i++)
{
for(int j = 0; j < niz2.length; j++)
{
if(niz[i] == niz2[j])
{
if(printed.indexOf(niz[i]) == -1) {
System.out.println(niz[i]+" ");
}
printed += niz[i];
}
}
}
A one liner :
HashSet<Character> common =
new HashSet<Character>(Arrays.asList(niz1)).retainAll(
new HashSet<Character>(Arrays.asList(niz2)));
Store the char in Set in
Set<Character> cs=new HashSet<>();
if(niz[i] == niz2[j])
{
cs.add(niz[i]);
//System.out.println(niz[i]+" ");
//What now!?!?!?
}
The value for the Morse Code translation keeps returning null and I've done everything I can think of to fix it. We are restricted to using arrays on this assignment. What can I do to correct it?
import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
public class morseCodeTest
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered
//object creation
Translate text = new Translate();
//getting user input to be translated
do
{
userInput = JOptionPane.showInputDialog("Please enter what you wish to translte to Morse code (no punctuation).");
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];
codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}while(!userInput.equals(SENTINEL));
}//end main
}//end class
class Translate
{
public Translate()
{
}//end default constructor
public String[] translateHere(String s)throws IOException
{
String compare = s, codedLine = ""; //userInput toUpperCase
int length = compare.length(); //length of userInput
String line, file = "Morse.txt";// variable holding file name and variable for each letter/number
char code;
//Constants
final int MAX = 36;
//Arrays
char[] morseLetter = new char[MAX];
String[] morseCode = new String[MAX];
String[] newMessage = new String[length];
//putting user input in a character array;
char[] userLetters = compare.toCharArray();
//object creation
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
//for loop that will read data from the Morse.txt file
for(int i = 0; i < MAX; i++)
{
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
morseLetter[i] = code;
morseCode[i] = inFile.next();
}//end nested while loop
}//end for loop
for(int j = 0; j < length; j++)
{
for(int k = 0; k < MAX; k++)
{
if(userLetters[j] == morseLetter[k])
{
newMessage[j] = morseCode[k];
}
}//end nested for loop
}//end for loop
return newMessage;
}//end method that completes translateion
public String toString(String a, String[] b)
{
String input = a;
String[] coded = b;
String[] encoded = new String[input.length()];
//JOptionPane.showMessageDialog(null, "Original Text: " + input + "\nCoded Text: " + coded);
for(int l = 0; l <input.length(); l++)
{
encoded[l] = coded[l];
}
String str = "";
System.out.print(Arrays.toString(encoded));
return str;
}//end toString method
}//end Translate Class
The Morse code text file contains the following:
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
0 -----
A .-
B -...
C -.-.
D -..
E .
F ..-.
G --.
H ....
I ..
J .---
K -.-
L .-..
M --
N -.
O ---
P .--.
Q --.-
R .-.
S ...
T -
U ..-
V ...-
W .--
X -..-
Y -.--
Z --..
Your Translate.toString method will always return an empty string because that's the only thing you assign to the str variable.
public String toString(String a, String[] b)
{
System.out.println("Input: " + a);
System.out.println("Output:");
String output = "";
for(int i = 0; i < b.length; i++)
{
output = output + b[i];
}
return output;
}//end toString method
But the real problem is this loop:
for(int i = 0; i < MAX; i++)
{
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
//System.out.println(code);
morseLetter[i] = code;
morseCode[i] = inFile.next();
}//end nested while loop
}//end for loop
There you try parsing the morse code letters into a file, but the problem is the for loop is in the first iteration and then, the whole while loop is executed, therefore you're always placing the morsecode in the first position of the array.
So it should look like that:
int counter = 0;
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
//System.out.println(code);
morseLetter[counter] = code;
morseCode[counter] = inFile.next();
counter++;
}//end nested while loop
As an additional note: Did you noticed that if the user clicks cancel in your OptionsDialog that there is a NullPointer? Proper exception handling is part of the assignment I think ;)
Therefore I would write the loop like this:
do
{
userInput = JOptionPane.showInputDialog("Please enter what you wish to translte to Morse code (no punctuation).");
if (userInput != null && !userInput.equals("")) {
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];
codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}
}while(userInput != null && !userInput.equals(SENTINEL));