I have this program but i have a few problems:
This is the place where i do the calcs.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class MorseCode {
public MorseCode()
{
}//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 = "C:\\APCS Course B\\Unit 4\\Unit 4 Documents\\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);
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
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)
{
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
}//end Translate Class
The main methods:
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
public class MorseCodeTester
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered
//object creation
MorseCode text = new MorseCode();
//getting user input to be translated
do
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter what you wish to translte to Morse code (no punctuation): ");
userInput = in.nextLine();
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
So my program is when I put in a input the output shows black even tho in the main methods i did the calculation that would convert it to Morse Code. Also is there any suggestions on if i could use the static identifier in any of my methods.
Here is the text file:
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 code should use a hashmap to key the morse code by letter, this makes your code much simpler.
Getting the morsecode for a letter is then a simple lookup.
Also you could just load the data once, maybe in the Constructor of MorseCode.
But to get at your question, you are just not printing the output. Just returning it and not showing it on the console.
if you change your toString method to look like this, it should print out something.
public String toString(String a, String[] b) {
System.out.println("Input: " + a);
System.out.print("Output:"); // changed to a print, to avoid newline
String output = "";
for (int i = 0; i < b.length; i++) {
output = output + b[i];
}
System.out.println(output); // this was missing
return output;
}//end toString method
Related
I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);
In this i need to take in a user imputed sentence and print it out in pig-latin.
(also i have several imports that aren't needed but I left them in when i copied the class and main lines from another program)
import static java.lang.System.*;
import java.util.*;
import java.lang.Math;
public class Pig_latin
{
public static void main(String[]args)
{
String sentence;
out.print("Enter a complete sentence: ");
Scanner sc = new Scanner(System.in);
sentence=sc.nextLine();
Here i am creating the string array and splitting at the spaces.
The only problem with this is that now each word is in its own object.
String s1[]=sentence.split(" ");
Because I've separated the words I don't know of a way to access each character to move them to the end or add "ay".
for(int x=0;x<s1.length;x++)
{
}
}
}
Heres a simple way of how you can get each character in a string in java. String.charAt(index) gets the current character at the index specified.
public static void main(String[] args) {
String getMyCharacters = "Hello World";
for(int i = 0; i < getMyCharacters.length();i++)
{
System.out.print(getMyCharacters.charAt(i));
}
}
output: Hello World
And this is one way of how you get the characters when you split each word into its own string.
String[] splitted = getMyCharacters.split(" ");
for(int j = 0; j < splitted.length; j++)
{
System.out.println("\nCurrent word:" + splitted[j]);
for(int y = 0; y < splitted[j].length(); y++)
{
System.out.println(splitted[j].charAt(y));
}
}
output:
Current word:Hello
H
e
l
l
o
Current word:World
W
o
r
l
d
You can refer each element of the array with s1[x], x is the index of the array s1, thereby saying you are looking up the xth element of the array.
for(int x=0;x<s1.length;x++)
{
System.out.println(s1[x]);
}
Even though this code compiles:
import java.util.Scanner; // imports the Scanner class from the java.util package
public class ScannerPractice {
public static void main(String args[]) {
Scanner word = new Scanner("word 1 2 3 4"); // creates a new Scanner objecrt with a string as its input
String scaStr = word.nextLine(); // converts scanner to string
String strArr[] = new String[10];
// as long as the scanner has another character...
for (int i = 0; i < scaStr.length(); i++) {
int j = 0;
String k = "";
// if the next token is an integer...
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
// otherwise, skip over that token
else {
word.next();
}
}
String k = "";
// for each character in charArr
for (int i = 0; i < strArr.length; i++) {
// Accumulate each element of charArr to k
k += " " + strArr[i];
}
System.out.print(k);
}
}
I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ScannerPractice.main(ScannerPractice.java:28)
The exception refers to line 28, which is:
word.next();
I have tried looking at my for loop that assigns values to the string array, but I still couldn't find the error.
I am racking my brain trying to solve this. Even a hint would be most appreciated.
You already consumed all the strings in your Scanner on this line.
String scaStr = word.nextLine();
So, the scanner doesn't have more characteres and that's why you are getting that error.
I think you don't need to 'convert your scanner to string' in order to iterate over it. You can simply use a while to check if your Scanner has remaining characteres.
while(word.hasNext()) {
int j = 0;
String k = "";
// if the next token is an integer...
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
// otherwise, skip over that token
else {
word.next();
}
}
Change the loop to check whether the scanner has any more input:
Scanner word = new Scanner("word 1 2 3 4");
String strArr[] = new String[10];
int i = 0;
while (word.hasNext()) {
int j = 0;
String k = "";
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
else {
word.next();
}
}
It doesn't make sense to iterate over the string you already consumed from the scanner, because then you lose the ability to match tokens. If you wanted to use a string tokenizer you could do that, but then you can drop using the scanner.
If you want your code to run correctly change the input to:
Scanner word = new Scanner("word"+"\n"+"1"+"\n"+"2"+"\n"+"3"+"\n"+"4");
adding newline character solves the problem.
Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.
Okay so I know there are other Morse code answers out there, but I have looked at many, but none of them worked. For my assignment I was to read a file, Morse.txt, into parallel arrays. Instead I just made two files, Morse.txt and Alphabet.txt one with code and the other with numbers and alphabet. I am supposed to use a class I made to do the translating part and when called in main it should translate user input. I can't seem to get this working. I've tried so many things from using a toString in the class or getter, but the return is not found when I put in the loop which I think has to be there(if that makes sense)..anyway here is my code for main:
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class redo
{
public static void main(String[]args) throws IOException
{
String line2, file2 = "Morse.txt";
String line, file = "Alphabet.txt";
File openFile = new File(file);
File openFile2 = new File(file2);
Scanner inFile = new Scanner(openFile);
Scanner inFile2 = new Scanner(openFile2);
int index = 36;
char[] charArray = new char[index];
String[] code = new String[index];
for(index = 0; index < 36; index++)
{
while(inFile.hasNext())
{
line = inFile.nextLine();
charArray = line.toCharArray();
//System.out.println(charArray[index]);
}
}
for(index = 0; index < 36; index++)
{
while(inFile2.hasNext())
{
code[index] = inFile2.nextLine();
//System.out.println(code[index]);
}
}
Scanner keyboard = new Scanner(System.in);
String userInput;
System.out.println("Enter something to translate: ");
userInput= keyboard.nextLine();
Translate inputTranslate = new Translate(userInput);
inputTranslate.setInput(userInput);
inputTranslate.setAlph(charArray);
inputTranslate.setCode(code);
inFile.close();
}
}
and here is my class Translate(some things are commented out):
public class Translate
{
String input;
String code[];
char alph[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(char[] alph)
{
this.alph = alph;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
// public String getTranslate()
// {
// for(int i = 0; i < input.length(); i++)
// {
// for(int index = 0; index < alph.length; index++)
// {
// if(input.charAt(i) == alph[index])
// {
// String output = code[index];
// }
// }
// }
// return output;
// }
}
Morse.txt:
.----
..---
...--
....-
.....
-....
--...
---..
----.
.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
-.
.--.
--.-
.-.
...
..-
...-
.--
-..-
-.--
--..
Alphabet.txt:
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
The problem is your return can't reach "output", you need to declare "output" above the loops and initialise it to output = null;
Even then it'll only send one string. So I did this;
public String getTranslate()
{
String output = null;
String[] translated = new String[input.length()];
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alph.length; index++)
{
if(input.charAt(i) == alph[index])
{
output = code[index];
translated[i] = output;
}
}
}
for (int j = 1; j < translated.length; j++) {
output = translated[0].concat(translated[j]);
}
return output;
}
This basically sticks all the codes together giving you your desired outcome.