java program won't output words - java

I'm trying to convert a text to nato alphabet but I can't figure out what is the problem. I tried to split the text into characters and then put it in arrays then in a for loop to test if the character is equal and write the correct word
Sample Text : hello
Result: hotel echo lima lima oscar
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to conver to nato :");
String text = scan.nextLine();
char[] carray = text.toCharArray();
for(int i=0;i<carray.length;i++){
if("a".equals(carray[i])){
System.out.print("alpha");
}if("b".equals(carray[i])){
System.out.print("brabo");
}if("c".equals(carray[i])){
System.out.print("charlie");
}
if("d".equals(carray[i])){
System.out.print("delta");
}if("e".equals(carray[i])){
System.out.print("echo");
} if("f".equals(carray[i])){
System.out.print("foxtrot");
}if("g".equals(carray[i])){
System.out.print("golf");
} if("h".equals(carray[i])){
System.out.print("hotel");
} if("i".equals(carray[i])){
System.out.print("india");
} if("j".equals(carray[i])){
System.out.print("juliet");
} if("k".equals(carray[i])){
System.out.print("kilo");
} if("l".equals(carray[i])){
System.out.print("lima");
} if("m".equals(carray[i])){
System.out.print("mike");
} if("n".equals(carray[i])){
System.out.print("november");
} if("o".equals(carray[i])){
System.out.print("oscar");
} if("p".equals(carray[i])){
System.out.print("papa");
} if("q".equals(carray[i])){
System.out.print("quebec");
} if("r".equals(carray[i])){
System.out.print("romeo");
} if("s".equals(carray[i])){
System.out.print("sierra");
} if("t".equals(carray[i])){
System.out.print("tango");
} if("u".equals(carray[i])){
System.out.print("uniform");
} if("v".equals(carray[i])){
System.out.print("victor");
} if("w".equals(carray[i])){
System.out.print("whiskey");
} if("x".equals(carray[i])){
System.out.print("x-ray");
} if("y".equals(carray[i])){
System.out.print("yankee");
} if("z".equals(carray[i])){
System.out.print("zulu");
}
}
}
}

Others have already pointed out in the comments that you're comparing a string to a char, which will never be equal. By way of illustration, try the following program:
public class Demo {
public static void main(String[] args) {
Boolean x = "b".equals('b');
System.out.println(x);
}
}
The result will be false. You could argue that this is a bit of a "gotcha" in Java, but that's a matter of opinion.
Also, if you have that many if statements in a row, it's a pretty good hint that something's probably gone wrong. At a minimum, a switch statement would be far easier to read:
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to convert to nato: ");
String text = scan.nextLine();
// You might want to consider converting the whole string to lowercase to make this case-insensitive
char[] carray = text.toCharArray();
for(int i=0; i < carray.length; i++){
if (i > 0)
{
// We need to prepend a space here
System.out.print(" ");
}
switch (carray[i])
{
case 'a': System.out.print("alpha"); break;
case 'b': System.out.print("bravo"); break;
// The rest of your cases go here
// Be sure to handle the case where the user enters something invalid
default: System.out.print(carray[i] + " is not a valid lowercase letter"); break;
}
}
}
}
As you can see, indenting the code properly, adding some extra whitespace, and using a switch statement makes this much easier to read.

Related

How to do repeated sequence check

Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}

How to stop storing integers and special characters in String in Java?

I wrote a program to read username from keyboard. When I enter any integer or special characters, it is taking that values and displaying on console. But I want that it should not take any integers and special characters. It should take only letters and if any integer or special character is there, then it should give the error message and should not store that value. Can anybody help me with this problem?
The program program which I wrote is
import java.util.Scanner;
public class CheckIsEmpty {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter User Name:: ");
System.out.println();
String usn = sc.nextLine();
if (usn.trim().isEmpty()) {
System.out.println("Don't Give Space");
System.out.println();
}//if
else if (usn.isEmpty()) {
System.out.println("User Name Is Mandatory");
System.out.println();
} // if
else {
System.out.println("Hi " + usn);
System.out.println("Welcome To Java");
break;
}// else
}//while
}//main
}// class
You can use regex here. If all characters are letters then following code will return true.
usn.matches("[a-zA-Z]+")
If an input string is having any other char it will return false.
Hope it helps.
You can use pattern matching..
boolean b = Pattern.compile("[a-zA-Z]+").matcher(username).matches();

String matching program

I am trying to make a java program to reverse the given string and each time iterate, compare with the reversed string then to print pass if matched else fail.
My program is:
package sss;
import java.util.Scanner;
public class ssi {
/**
* #param args
*/
public static void main(String[] args) {
String original,reverse="";
Scanner sc=new Scanner(System.in);
int ascii11,ascii12,ascii13,ascii14;
System.out.println("enter the string to be reversed");
original=sc.next();
int length=original.length();
for(int i=length-1;i>=0;i--)
{
reverse=reverse+original.charAt(i);
}
System.out.println(reverse);
//System.out.println(original);
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}
// TODO Auto-generated method stub
sc.close();
}
}
here each time when the for loop iterates i am getting pass or fail for each pair of numbers but i want the o/p as to print only pass or fail ONCE.
can any one help me out please...
Example Code:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
String original;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string to be reversed: ");
original = sc.next();
int halfLength = original.length()/2;
int lastIndex = original.length() - 1;
int i;
for(i = 0; i < halfLength; i++) {
if(original.charAt(i) != original.charAt(lastIndex - i)) {
System.out.println("Fail!");
break;
}
}
// Managed to match all characters
if(i == halfLength) {
System.out.println("Pass!");
}
sc.close();
}
}
Input/Output:
Enter the string to be reversed: banana
Fail!
Enter the string to be reversed: RADAR
Pass!
Enter the string to be reversed: asdwwdsa
Pass!
So the idea is to:
Compare the first half of the string with the second half of the string
Compare the first character with the last character
Compare the 2nd character with the 2nd last character, and so on.
If any character does not match, print Fail!
If the loop finishes, it implies that the string is a palindrome (original == reversed), print Pass!
You need to flag each comparison of the original and reversed characters with either a pass or a fail boolean value. Obviously if any of them are flagged with a fail, you can then terminate the algorithm and print fail. If the for loop continues with a pass right to the end, then print pass once outside of the for loop.
Your print statement is inside the loop , so its printing "pass" or "fail" for each loop. You should use a flag to check whether all the ascii characters are same. and then check the status of flag outside the loop.
OR
Use StringBuffer it has a built-in method to reverse string.
StringBuffer input = new StringBuffer("Your String to reverse");
String reverse = input.reverse().toString();
if(input.equals(reverse))
System.out.println("pass");
else
System.out.println("fail");
Move your if condition out of for loop.
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
}
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}

I need to convert a void out put into a string so that i can compare the two strings

My program is supposed to generate a pattern of letters based on the input of the user. I have to use recursion to set each output to be different. I've already done this. Next i have to compare the two outputs in another method and use recursion to find the length of the longest common sub sequence between the two. The problem is i dont know how to compare them. Since they are void results i dont know how to convert them to strings.
import java.util.Scanner;
public class patternOfLetters {
private static String letter;
public static void printLetterPattern(char letter){
char [] pattern = new char[1];
int patternLength= pattern.length;
String result="";
char start=letter;
if(start=='A'){
System.out.print('A');
result+='A';
}else if(start=='B'){
printLetterPattern('A');
System.out.print('B');
printLetterPattern('A');
}
else if(start=='C'){
printLetterPattern('B');
System.out.print('C');
printLetterPattern('B');
}
else if(start=='D'){
printLetterPattern('C');
System.out.print('D');
printLetterPattern('C');
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Scanner otherIn = new Scanner(System.in);
System.out.println("Enter a character to start the pattern: ");
String input = in.nextLine();
String upper = input.toUpperCase();
char letter=upper.charAt(0);
System.out.println("");
System.out.println("Your first pattern of letters is:");
printLetterPattern(letter);
System.out.println("");
System.out.println("");
System.out.println("Enter another character to generate your second pattern: ");
String input2 = in.nextLine();
String upper2 = input2.toUpperCase();
char letter2=upper2.charAt(0);
System.out.println("");
System.out.println("Your second pattern of letters is:");
printLetterPattern(letter2);
in.close();
otherIn.close();
}
}//fin.
You cant, return type "void" means there is no result returned, so there is nothing you could convert.
Your methods just print their output to the console, you will need to rewrite them so they actually return a result.
One way could be like this (pseudocode):
public String produceLetterPattern(String pattern, char letter) {
...
if(start=='A') {
pattern+="A";
return pattern;
} else if (start=='B') {
pattern = produceLetterPattern(pattern, 'A');
pattern +="B";
pattern = produceLetterPattern(pattern, 'A');
return pattern;
} ...
}
That's the general idea, you should be able to work it out from there. Important part is that you need a result returned, in the above example a String, returned via
return pattern;

Setting a parameter for returned string values

I am trying to create a game where a user enters a phrase, but the phrase can only be in lower case letters (if you catch my drift). So the program will prompt the user with a do-while loop. If the user enters anything like (1234567890, or !##$%^&* or ASDFGH, the loop should re-prompt for the user to enter only lower case letters. I am extremely new to java, so my code is going to be really shitty. Here is is:
import java.util.Scanner;
public class Program05
{
public static void main(String[] args)
{
Scanner scanner01 = new Scanner(System.in);
String inputPhrase;
char inputChar;
do {
System.out.print("Enter a common phrase to begin!: ");
inputPhrase = scanner01.nextLine();
} while (!inputPhrase.equals(Character.digit(0,9)));
}
}
Use String.matches() with the appropriate regex to test if it's all lowercase letters:
inputPhrase.matches("[a-z ]+") // consists only of characters a-z and spaces
So your loop would look like:
do {
System.out.print("Enter a common phrase to begin!: ");
inputPhrase = scanner01.nextLine();
} while (!inputPhrase.matches("[a-z ]+"));
Try this i compiled this and it worked well
public static void main(String[] args)
{
Scanner scanner01 = new Scanner(System.in);
String inputPhrase = "";
char inputChar;
while(!inputPhrase.equals("exit")){
System.out.print("Enter a common phrase to begin!: ");
inputPhrase = scanner01.nextLine();
for(int i = 0; i < inputPhrase.length(); i++){
if(!Character.isLetter(inputPhrase.charAt(i))
||Character.isUpperCase(inputPhrase.charAt(i))){
System.out.println("Input must be lowercase characters");
break;
}
}
}
}
}

Categories