I am taking input from user in string and I want to iterate and test using case statement but it is not working. its not printing the statements.
import java.io.*;
import java.util.*;
public class fh3
{
public static void main(String args[])throws IOException
{
String sentence = "";
System.out.println("Enter the word : ");
Scanner scan = new Scanner(System.in);
String word = scan.next();
char[] chars = word.toCharArray();
for(int i = 0; i < word.length(); i++)
{
System.out.println("---" + chars[i]);
switch(chars[i])
{
case 0: sentence = " ";
System.out.println("B");
break;
case 1: sentence = "A";
break;
case 2: sentence = "B";
System.out.println("B");
break;
case 3: sentence = "C";
break;
}
sentence+=sentence;
System.out.println(sentence);
}
}
}
if i enter 20 den it should print"B "
but its printing as
Enter the word :
20
---2
---0
where i am getting wrong?
Since you're doing the switch on char type, your case should have the same. In your case, since you give the case as integer values, its just not matching. '0' is not equal to 0
switch(chars[i]) {
case '0': // switch on char '0' and not integer 0.
case '1': // switch on char '1' and not integer 1.
case '2': // switch on char '2' and not integer 2.
...
}
import java.io.IOException;
import java.util.Scanner;
public class Fh3 {
public static void main(String args[]) throws IOException {
String sentence = "";
System.out.println("Enter the word : ");
Scanner scan = new Scanner(System.in);
String word = scan.next();
//Switch case needs you to compare the expression with constants hence the final keyword.
final char CHARONE = '1';
final char CHARTWO = '2';
final char CHARTHREE = '3';
final char CHARFOUR = '4';
char[] chars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
System.out.println("---" + chars[i]);
switch (chars[i]) {
case 0:
sentence = " ";
System.out.println("B");
break;
case CHARONE:
sentence = "A";
break;
case CHARTWO:
sentence = "B";
System.out.println("B");
break;
case CHARTHREE:
sentence = "C";
break;
}
sentence += sentence;
System.out.println(sentence);
}
}
}
You were trying to compare int with char .. Clear ?
Because you're switching on characters, not integers :
switch(chars[i]){
case '0': sentence = " ";
System.out.println("B");
break;
case '1': sentence = "A";
break;
case '2': sentence = "B";
System.out.println("B");
break;
case '3': sentence = "C";
break;
}
your switch is accepting char but no suitable case is there.So its printing only this statement System.out.println("---" + chars[i]); two times(because word.length() returns 2 in your case)
import java.io.*;
import java.util.*;
public class fh3
{
public static void main(String args[])throws IOException
{
String sentence = "";
System.out.println("Enter the word : ");
Scanner scan = new Scanner(System.in);
String word = scan.next();
char[] chars = word.toCharArray();
for(int i = 0; i < word.length(); i++)
{
System.out.println("---" + chars[i]);
switch(chars[i])
{
case '0': sentence = " ";
System.out.println("B");
break;
case '1': sentence = "A";
break;
case '2': sentence = "B";
System.out.println("B");
break;
case '3': sentence = "C";
break;
}
sentence+=sentence;
System.out.println(sentence);
}
}
}
In Java, the char type maps to the int type via the Ascii table.
Therefore, if you want to check the char '0' and not the NUL char, you should do:
switch(chars[i]) {
case '0': // do the work
case '1': // do the work
// ...
}
Related
Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));
Here I have created a flames game logic it is final string length is correct(eg:4 for two strings 'raja' and 'rani') based on length I need to show 'f' or 'l' or 'a' or 'm' or 'e' or 's'.
I have written logic based on length that character is visible but that is not my concern. For length 4 result should be 'e'(in flames for length 4 first 'm' should remove then 'l' then 'f' then 'a' then 's' finally i need 'e' as output.Can anybody tell me idea. This is my code.
public static void main(String[] args) {
String name1 = "raja";
String name2 = "rani";
String s1 = name1;
String s2 = name2;
for (int i = 0; i < name1.length(); i++) {
for (int j = 0; j < name2.length(); j++) {
if (name1.charAt(i) == name2.charAt(j)) {
name1 = name1.replaceFirst(String.valueOf(name1.charAt(i)), "#");
name2 = name2.replaceFirst(String.valueOf(name2.charAt(j)), "#");
}
}
}
String result = name1 + name2;
result = result.replaceAll("#", "");
int resultLength = result.length();
String baseInput = "flames";
char relationIs = 0;
int temp = 0;
if (resultLength > 0) {
temp = resultLength % baseInput.length();
}
if (temp == 0 && resultLength >= 6) {
relationIs = 's';
} else {
int count = temp - 1;
if (count >= 0) {
relationIs = baseInput.charAt(count);
System.out.println("Relation Betw " + s1 + " and " + s2 + " is:");
}
}
switch (relationIs) {
case 'f':
System.out.println("friendship");
break;
case 'l':
System.out.println("Lovers");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemity");
break;
case 's':
System.out.println("Siblings");
break;
default:
System.out.println("FLAME Test works only for different names");
break;
}
}
Logic follows this order:only forward direction remove 4 character.
if length=4
step 0:flames ('f' as 1)
step 1:flaes (here 'e' as 1)
step 2:faes (here 'a' as 1)
step 3:aes (here 'a' as 1)
step 4:es (here 'e' as 1)
step 5:e //output.
Your help will be appreciated.
Hope this is what you need. I am here striking the character of the word flames until i am getting one character. Once i get the character that is what the result of flames.
if (resultLength > 0) {
while (baseInput.length() !=1)
{
System.out.println(baseInput);
int tmpLen = resultLength % baseInput.length(); //finding char position to strike
if(tmpLen != 0)
{
temp = baseInput.substring(tmpLen) + baseInput.substring(0, tmpLen-1); //Append part start from next char to strike and first charater to char before strike.
}
else
{
temp = baseInput.substring(0, baseInput.length()-1); //If mod result zero we can strike last letter easily
}
baseInput = temp; //Assign the temp to baseinput for next iteration.
}
relationIs = baseInput.charAt(0);
System.out.println(relationIs);
}
Link : http://ideone.com/Fqgcc1
I think the problem is with this line:
int count = temp - 1;
Which is giving you an answer of 3 which gives (0)F (1)L (2)A (3)M
So change it to:
int count = temp; //- 1;
To get (0)F (1)L (2)A (3)M (4)E
// Another Right Code to Find FLAMES in JAVA
// It is simple
import java.util.Scanner;
class Flames
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
String name,fname,flm="flames";
System.out.println("Enter the boy name...");
name=sc.next();
System.out.println("Enter the girl name...");
fname=sc.next();
int l=name.length();
int gl=fname.length();
int num=0,tl=0;
char n[]=name.toCharArray();
char gn[]=fname.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<gl;j++)
{
if(n[i]==gn[j])
{
n[i]='*';
gn[j]='*';
break;
}
}
}
String tname=new String(n);
tname=tname+(new String(gn));
tname=tname.replace("*","");
tl=tname.length();
System.out.println(tl);
for(int s=6;s>=2;s--)
{
if(tl>s)
num=tl-s;
else
num=tl;
while(num>s)
{
num=num-s;
}
flm=flm.substring(num,flm.length())+(flm.substring(0,num-1));
}
switch(flm.charAt(0))
{
case 'f': System.out.println("Relationship = Friends"); break;
case 'l': System.out.println("Relationship = Lovers"); break;
case 'a': System.out.println("Relationship = Affections"); break;
case 'm': System.out.println("Relationship = Married"); break;
case 'e': System.out.println("Relationship = Enemy"); break;
case 's': System.out.println("Relationship = Brother & Sisters"); break;
}
//System.out.println("Name ="+flm);
}
}
import java.util.Scanner;
public class Flames {
public static void main(String[] args) {
/* Check the flames using two names */
Scanner scan = new Scanner(System.in);
System.out.print("Enter Name 1 : ");
String Name1 = scan.nextLine();
//System.out.println(Name1);
System.out.print("Enter Name 2 : ");
String Name2 = scan.nextLine();
//System.out.println(Name2);
int N1len = Name1.length();
int N2len = Name2.length();
Name1 = Name1.toLowerCase();
Name2 = Name2.toLowerCase();
StringBuffer NameB1 = new StringBuffer(Name1);
StringBuffer NameB2 = new StringBuffer(Name2);
int Name3=0;
for (int i = 0; i<N1len; i++)
{
for (int j = 0; j<N2len; j++)
{
if (NameB1.charAt(i) == NameB2.charAt(j))
{
NameB1 = NameB1.deleteCharAt(i);
NameB2 = NameB2.deleteCharAt(j);
N1len= NameB1.length();
N2len= NameB2.length();
i=0;
j=0;
}
}
}
Name3= NameB1.length()+NameB2.length();
//System.out.println(NameB1);
//System.out.println(NameB2);
//System.out.println(Name3);
/* Flames Calculation */
char flameResult =0;
String flames = "flames";
StringBuffer sb3 = new StringBuffer(flames);
while (sb3.length()!=1)
{
int Name4 = Name3%sb3.length();
String temp;
if(Name4!=0)
{
temp = sb3.substring(Name4)+sb3.substring(0, Name4-1);
}
else
{
temp=sb3.substring(0,sb3.length()-1);
}
sb3 = new StringBuffer(temp);
flameResult=sb3.charAt(0);
}
switch(flameResult)
{
case 'f': System.out.println("Friends");
break;
case 'l':
System.out.println("Love");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemies");
break;
case 's':
System.out.println("Sibling");
break;
}
}
}
import java.util.*;
public class Flames
{
public static void main()
{
int sp=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter two names");
String s=sc.nextLine().toLowerCase();
String s1=sc.nextLine().toLowerCase();
String p="flames";
String p1="flames";
String s2="";
String m="";
for(int i=0;i < s.length();i++)
{
if(Character.isLetter(s.charAt(i)))
{
m=m+s.charAt(i);
}
}
s=m;
m="";
for(int i=0;i < s1.length();i++)
{
if(Character.isLetter(s1.charAt(i)))
{
m=m+s1.charAt(i);
}
}
s1=m;
m="";
int l=s.length();
int l1=s1.length();
for(int i=0;i < l;i++)
{
int sl=0;
for(int j=0;j < s1.length();j++)
{
if(s.charAt(i)==s1.charAt(j))
{
if(sl==0)
{
sl++;sp++;s2=s2+" " ;
}
else
{
s2=s2+s1.charAt(j);
}
}
else
{
s2=s2+s1.charAt(j);
}
}
s1=s2;
s2="";
}
sp=sp*2;
int c=(l-1)+(l1-1)-(sp-1);
for(int i=1;;i++)
{
String z="";p=p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p;
String mn="";
char c1=p.charAt(c);
for(int j=0;j < p1.length();j++)
{
if(c1==p1.charAt(j))
{
mn=p1.substring(j+1)+mn;
break;
}
else
{
mn=mn+p1.charAt(j);
}
}
for(int k=0;k < p1.length();k++)
{
if(c1==p1.charAt(k))
{
}
else
{
z=z+p1.charAt(k);
}
}
p1=z;
p=mn;
if(mn.length()==1)
{
System.out.println(mn);
break;
}
}
}
}
I have a program that finds the number of times that four letters occur in a .txt file and I cannot figure out why it is giving me this error:
Error: The method isWhiteSpace(char) is undefined for the type java.lang.Character
What does this error mean, what is causing this problem, and how do I fix it?
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public class Count
{
public static void main (String[] args) throws FileNotFoundException {
String phrase;
String everything = ""; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
int countA;
int countE;
int countS;
int countT;
java.io.File file = new java.io.File("counting.txt");
Scanner inFile = new Scanner (file);
Scanner scan = new Scanner(System.in);
phrase = inFile.nextLine();
length = phrase.length();
// Initialize counts
while (true)
{
if (phrase.equalsIgnoreCase("quit"))
break;
else
{
countBlank = 0;
countA = 0;
countE = 0;
countS = 0;
countT = 0;
for ( int i = 0; i < length; i++ )
{
if ( phrase.charAt( i ) == ' ' )
countBlank++;
ch = phrase.charAt(i);
switch (ch)
{
case 'a':
case 'A': countA++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
case 't':
case 'T': countT++;
break;
}
}
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
System.out.println ("Number of A's: " + countA);
System.out.println ();
System.out.println ("Number of E's: " + countE);
System.out.println ();
System.out.println ("Number of S's: " + countS);
System.out.println ();
System.out.println ("Number of T's: " + countT);
break;
}
}
}
}
You have a typo it is Character.isWhitespace(ch);
The method isWhiteSpace(char) accepts an argument whose type is char, not Character.
Character is an object and char is a native type.
If char1 is the object of type Character, then use this code:
//Assume char1 is an object of type Character
boolean flagWS;
flagWS = Character.isWhiteSpace(char1.charValue())
I want to make a program that takes a string and encrypts it.
During execution of program it is supposed to convert a string to char array. Then, a switch statement runs through the array to replace a with b and vice versa.
However, the programm just returns the same as at the start! here is the code
import java.lang.*;
import java.util.Scanner;
public class Program
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String pw = input.next();
char pwa[] = pw.toCharArray();
for(char c : pwa ){
switch(c){
case 'a':
c = 'b';
break;
case 'b':
c ='a';
break;
}
}
String convpw = new String(pwa);
System.out.println(convpw);
}
}
You're just changing the variable c, not pwa, and c is local to your loop.
You can do this :
for (int i=0; i<pwa.length; i++) {
switch(pwa[i]){
case 'a':
pwa[i] = 'b';
break;
case 'b':
pwa[i] ='a';
break;
}
}
How do I use a character in a switch-case? I will be getting the first letter of whatever the user inputs.
import javax.swing.*;
public class SwitchCase {
public static void main (String[] args) {
String hello = "";
hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello;
switch(hi) {
case 'a': System.out.println("a");
}
}
}
public class SwitCase {
public static void main(String[] args) {
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); // get the first char.
switch(hi) {
case 'a': System.out.println("a");
}
}
}
charAt gets a character from a string, and you can switch on them since char is an integer type.
So to switch on the first char in the String hello,
switch (hello.charAt(0)) {
case 'a': ... break;
}
You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).
Using a char when the variable is a string won't work. Using
switch (hello.charAt(0))
you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside
case 'a '