Thanks for the help guys. Looked into arrays. Think I have it, but I'm having a hard time with getting it to print out. Any ideas? It prints out the word test, but only after several spaces (assuming thats where my letters are supposed to show up) Came up with this:
import java.util.Scanner;
public class q1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] aArray = new char[10];
String[] Acypher = { "D", "D", "W", "E", "L", "H", "O", "R" };
for (int i = 0; i < 10; ++i) {
int input = in.nextInt();
switch (input) {
case 1:
String newin1 = Acypher[1];
break;
case 2:
String newin2 = Acypher[2];
break;
case 3:
String newin3 = Acypher[3];
break;
case 4:
String newin4 = Acypher[4];
break;
case 5:
String newin5 = Acypher[5];
break;
case 6:
String newin6 = Acypher[6];
break;
case 7:
String newin7 = Acypher[7];
break;
default:
System.out.println("Translation unknown. Please enter a new number.");
--i;
break;
}
}
String aArrayDc = new String(aArray);
System.out.println(aArrayDc + "test");
}
}
This is a possible solution, but next time do your homework without asking for the solution
import java.util.Scanner;
public class q1 {
public static void main(String[] args) {
char[] cipher = { 'D', 'W', 'E', 'L', 'H', 'O', 'R' };
char decoded[] = new char[10];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 10; ++i) {
int num;
do {
num = in.nextInt();
} while (num < 1 || num > 7);
decoded[i] = cipher[num - 1];
}
System.out.println(decoded);
}
}
You'll probably want to rewrite your iterations to a for loop.
for(int i = 0; i < 10; ++i)
{
int input = in.nextInt();
//switch statement
}
You need to use a switch statement to find the letter for each number, we add a default case to handle an incorrect number.
This switch goes in the for loop.
switch(input)
{
case 1:
//store letter to array
break;
...
default:
--i;
System.out.println("Incorrect number, please enter a new number");
}
To store the letter of each match, we create an array, we already know it needs a length of 10.
This line goes before the for loop:
char[] decodedCharacters = new char[10]
Put this one in each switch statement:
decodedCharacters[i] = "D"; //another letter for each case.
And this one is to print all characters:
String decodedString = new String(decodedCharacters);
System.out.println(decodedString);
EDIT:
See #Guillaume 's answer for an approach leaving more flexibility for other combinations.
His answer doesn't handle an incorrect number though.
Related
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
I am creating a decoder program that will essentially turn numbers into specific letters using a while loop but I'm having difficulties figuring out what's wrong with my code and also if there is a simpler way to put it using switch for example. Here is what I have so far:
import java.util.Scanner;
public class Decoder{
public static String decode(String str){
int i = 0;
while(i<str.length()){
if(str.charAt(i)=='1')
return("D");
else if(str.charAt(i)=='2')
return("W");
else if(str.charAt(i)=='3')
return("E");
else if(str.charAt(i)=='4')
return("L");
else if(str.charAt(i)=='5')
return("H");
else if(str.charAt(i)=='6')
return("O");
else if(str.charAt(i)=='7')
return("R");
return("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
public static void main(String[] args){
System.out.println("Enter a number ");
}
}
Sure. Use a constant char array as a lookup table.
At index 0, store 'D'. At index 1, store 'W', etc.
Whenever you encounter a number in the source, subtract '1' to it to get the index in the array for this number, and get the matching letter from the array.
The code is left as an exercise.
Other than the array mentioned by JB Nizet, you could try:
switch statement
a Map<Integer, String> containing the digit/letter pairs
You can use StringBuilder and switch/case like that:
public class Decoder {
public static String decode(String str) {
int i = 0;
StringBuilder decodedString = new StringBuilder();
while (i < str.length()) {
switch (str.charAt(i)) {
case '1':
decodedString.append("D");
break;
case '2':
decodedString.append("W");
break;
case '3':
decodedString.append("E");
break;
case '4':
decodedString.append("L");
break;
case '5':
decodedString.append("H");
break;
case '6':
decodedString.append("O");
break;
case '7':
decodedString.append("R");
break;
default:
return ("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
return decodedString.toString();
}
public static void main(String[] args) {
while (true) {
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
System.out.println(decode(input.next()));
System.out.println();
}
}
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;
}
}
}
}
The objective is to count how many vowels there are in the phrase that the user inputs.
The user will input a phrase which will be
my name is nic
The output will be for this example is
Vowel Count: 4
Now here is my code.
import cs1.Keyboard;
public class VowelCount {
public static void main(String[] args) {
System.out.println("Please enter in a sentence.");
String phrase = Keyboard.readString();
char[] phraseArray = phrase.toCharArray();
char[] vowels = new char[4];
vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
int vCount = countVowel(phrase, phraseArray, vowels);
System.out.println("Vowel Count: " + vCount);
}
public static int countVowel(String word, char[] pArray, char[] v) {
int vowelCount = 0;
for (int i = 0; i < word.length(); i++) {
if (v[i] == pArray[i])
vowelCount++;
}
return vowelCount;
}
}
With my code I am getting an ArrayIndex Error. I know the fix but when I change
for (int i = 0; i < word.length(); i++) {
to
for (int i = 0; i < 5; i++) {
It fixes the error but does not count the vowels. It outputs
Vowel Count: 0
So how can I fix this problem and is there a better way to do this than the way I am attempting to do it?
Just use regular expression. will save you a lot of time
int count = word.replaceAll("[^aeiouAEIOU]","").length();
You are attempting to store five vowels in a four vowel array;
char[] vowels = new char[5]; // not 4.
vowels[0] = 'a'; // 1
vowels[1] = 'e'; // 2
vowels[2] = 'i'; // 3
vowels[3] = 'o'; // 4
vowels[4] = 'u'; // 5
Or,
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
Also, don't forget to call toLowerCase() or you'll only count lower case vowels.
Finally, you should be looping over each character in pArray and each vowel. I'd use two for-each loops like
for (char ch : pArray) {
for (vowel : v) {
if (ch == v) vowelCount++;
}
}
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
// ...
}