How to convert certain characters in a sentence using if else statements? - java

my program so far only works if you enter one letter. How would I alter the program so it works with a complete sentence?
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
if(convert.equals("a")){
System.out.print("#");
}
else{
if(convert.equals("e")){
System.out.print("$");
}
An example:
Enter the string to be converted: abcde
The converted string is: #bcd$

Your program will work only for an input consisting of one character e.g. if you input a, it will print # and if you input e, it will print $ and so on (if you add other vowels too in your program). It is because you are comparing (and replacing) the whole input string rather than comparing (and replacing) the character(s) of the input string.
There are many ways in which you can do it. A couple of them are as follows:
Get an array of characters out of the input string and then iterate the array to process the printing as per your requirement e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
for (char ch : convert.toCharArray()) {
switch (ch) {
case 'a':
System.out.print('#');
break;
case 'e':
System.out.print('$');
break;
case 'i':
System.out.print('^');
break;
case 'o':
System.out.print('*');
break;
case 'u':
System.out.print('&');
break;
default:
System.out.print(ch);
}
}
}
}
A sample run:
Enter the string to be converted: coronavirus
c*r*n#v^r&s
Replace the characters as per your requirements using String::replace e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string to be converted: ");
String convert = input.nextLine();
convert = convert.replace('a', '#').replace('e', '$').replace('i', '^').replace('o', '*').replace('u', '&');
System.out.println(convert);
}
}
A sample run:
Enter the string to be converted: coronavirus
c*r*n#v^r&s

You have to add this instead of your if sentences:
for (int i = 0; i < convert.length(); i++ { //This loop will repeat the same times that the String's lenght
switch (convert.charAt(i) {
case 'a': System.out.print("#");
break;
case 'e': System.out.print("$");
break;
case 'i': System.out.print("&");
break;
case 'o': System.out.print("#"); // Here you put the letter to replace.
break;
default: // This code will execute if there's a option you didn't put on the cases
}
}

Related

Decrease the space complexity of finding certain letters in String in Java

Problem
I have a problem that finding certain letters in a given String cost too much memory which caused a "Memory Limit Exceeded". I am wondering the reason of it. The question and my codes are below.
Question
describe: Find the number of times the vowels a, e, i, o, u appear in a string.
Enter: Enter a line of string, the string length is less than 80 characters. So the characters are all lowercase letters.
Output: Output a line, and output the number of times a, e, i, o, u appear in the input string in sequence, and the integers are separated by spaces.
Codes
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] count = new int[5]; // refers to 'a' 'e' 'i' 'o' 'u'
Scanner buf = new Scanner(System.in);
String input = buf.nextLine();
buf.close();
for(int i = 0; i < input.length(); i++) {
switch(input.charAt(i)) {
case 'a':
++count[0];
break;
case 'e':
++count[1];
break;
case 'i':
++count[2];
break;
case 'o':
++count[3];
break;
case 'u':
++count[4];
break;
}
}
for(int item: count) {
System.out.print(item);
System.out.print(' ');
}
}
}
Summary
Deleted the call of the Scanner class and read characters one by one directly from System.in
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
int[] count = new int[5]; // a e i o u
int temp = System.in.read();
while(temp != '\n') {
switch(temp) {
case 'a': // 97
++count[0];
break;
case 'e':
++count[1];
break;
case 'i':
++count[2];
break;
case 'o':
++count[3];
break;
case 'u':
++count[4];
break;
}
temp = System.in.read();
}
// System.in.close();
for(int item: count) {
System.out.print(item);
System.out.print(' ');
}
}
}

Java - Assign a number and a word to a string of inputted characters

I am new to Java and I am trying to make a program that will take a string, such as 'asdfg', and print words and a total number that are associated with these letters.
So 'a' would be 'apple' and its assigned number is 10, 's' would be spinach, and its assigned number is 5, 'd' would be 'dog' and its assigned number would be 15, 'f' would be 'frog' and its assigned number would be 20 and 'g' would be 'goat' and its assigned number would be 25. The output would look something like 'apple spinach dog frog goat 75'.
The code I have so far is
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class PizzaTwo {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the details of your order");
String myList = scan.nextLine();
for (int i = 0; i < myList.length(); i++) {
int letNum = 0;
switch (myList.charAt(i)) {
case 'a':
System.out.println("apple" + letNum);
letNum += 10;
break;
case 's':
System.out.println("spinach" + letNum);
letNum += 5;
break;
case 'd':
System.out.println("dog" + letNum);
letNum += 15;
break;
case 'f':
System.out.println("frog" + letNum);
letNum += 20;
break;
case 'g':
System.out.println("goat", letNum);
letNum += 25;
break;
default:
System.out.println("Nothing..");
break;
}
}
}
}
Thank you for any help.
First of all, I'd like to suggest you use better names for variables.
You were resetting the "letNum" in each loop, then I've moved it out of the loop.
I recommend read about String and StringBuilder.
String objects are immutable, so instead to create more variables to concatenate "flavors", I used StringBuilder that are mutable.
Strings are constant; their values cannot be changed after they are created
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type
import java.util.Scanner;
public class PizzaTwo {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the details of your order");
String flavors = scan.nextLine();
int price = 0;
StringBuilder order = new StringBuilder();
for (int i = 0; i < flavors.length(); i++) {
switch (flavors.charAt(i)) {
case 'a':
order.append("apple ");
price += 10;
break;
case 's':
order.append("spinach ");
price += 5;
break;
case 'd':
order.append("dog ");
price += 15;
break;
case 'f':
order.append("frog ");
price += 20;
break;
case 'g':
order.append("goat ");
price += 25;
break;
default:
order.append("No flavor added ");
break;
}
}
System.out.println(order.append(price));
}
}
It looks like you want the numbers to only appear after all the words have been printed, from your description "apple spinach dog frog goat 75", but your code looks like it's trying to append the number to the end of each word.Assuming you want the output to be like your sample output, don't try to print the numbers after each word, instead after all the words have been printed print the variable you've been using to accumulate each letters value, 'letNum' in your code.Also, don't reset 'letNum' each time you deal with a new letter.
Take 2 separate variables, 1 string and another number. Each time concatenate with existing string, means something like String s=""; int n=0; s+="Apple"; n+=10; s+="frog";
....
Now when loop is done print string then the number.

Want to create a condition that checks were the input is a integer ranging from 1 to 5

I Want to create a condition that checks were the input is a integer ranging from 1 to 5.
but it keeps saying input matching exception, can you guys help?
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(">> You have selected ["+choice+"]");
//loops until input is an integer ranging from 1 to 5
while(!scan.hasNextInt() && choice>0 && choice<6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
break;
}
}
}
Try this:
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
//input variable
String in;
//loops until input is an integer ranging from 1 to 5
while (scan.hasNextLine()) { //checks if there is a new line of input
in = scan.nextLine().trim(); //scans that line
if (!in.matches("^[1-5]$")) { //tests if input is a single positive digit 1-5
System.out.println(">> You put wrong input");
continue;
}
int choice = Integer.parseInt(in);
System.out.println(">> You have selected ["+choice+"]");
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
}
}
}
}
I have slightly altered your code to not only keep persisting the user for a valid input, but also correctly parse that input to avoid any errors. I also removed the default part of the switch block, only because the input validation prior eliminates the need for it.
I have not tested this code, but it should work properly :)
You are currently not updating the choice variable for each iteration, but rather only using the initial value. Furthermore, you're iterating until scan DOES NOT have an int, i.e. !scan.hasNextInt() and I guess you're intention is actually the opposite.
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice;
//loops until input is an integer ranging from 1 to 5
while(scan.hasNextInt() && (choice = scan.nextInt()) > 0 && choice < 6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
}
}
}
Hope it helps!

Java: How to deal with string index out of range error?

I'm new to Java and I can't figure out how to solve this problem:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
Here's the entire code:
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
//Step 1: Ask user to enter first and last name
System.out.println("\nPlease enter your first and last name: ");
String name = input.nextLine();
String major = "";
String classification = "";
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
char ch = input.next().charAt(0);
char ch1 = input.nextLine().charAt(1);
//Step 3: Print statement
switch(ch) {
case 'i': major = "Information Technology"; break;
case 'c': major = "Computer Science"; break;
case 'm': major = "Mathematics"; break;
case 'p': major = "Physics"; break;
case 'b': major = "Biology"; break;
case 'e': major = "Engineering"; break;
case 'h': major = "History"; break;
case 'j': major = "Journalism"; break;
case 'a': major = "Art and Design"; break;
case 'l': major = "Literature"; break;
case 's': major = "Sport Medicine"; break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1) {
case '1': classification = "Freshman"; break;
case '2': classification = "Sophmore"; break;
case '3': classification = "Junior"; break;
case '4': classification = "Senior"; break;
case '5': classification = "Graduate"; break;
default: System.out.println("\nInvalid Classification Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
System.out.println("\nMajor and classification is: " + major + "" + classification);
System.out.println("\nThank You!");
}//end of main
Any help would be greatly appreciated.
Try to change your code so that it first checks for the length of the input before it refer to the index of the String. Something like the following:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String inputNext = input.next();
String inputNextLine;
if(inputNext.length>0 && inputNextLine.length>0){
char ch = inputNext;
char ch1 = inputNextLine;
//Step 3: Print statement
switch(ch)
{
case 'i': major = "Information Technology";
break;
case 'c': major = "Computer Science";
break;
case 'm': major = "Mathematics";
break;
case 'p': major = "Physics";
break;
case 'b': major = "Biology";
break;
case 'e': major = "Engineering";
break;
case 'h': major = "History";
break;
case 'j': major = "Journalism";
break;
case 'a': major = "Art and Design";
break;
case 'l': major = "Literature";
break;
case 's': major = "Sport Medicine";
break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1)
{
case '1': classification = "Freshman";
break;
case '2': classification = "Sophmore";
break;
case '3': classification = "Junior";
break;
case '4': classification = "Senior";
break;
case '5': classification = "Graduate";
break;
}
}
The problem is that char ch = input.next().charAt(0); will read both the characters, but not "consume" the newline character that is generated when the user hits Enter.
You then call input.nextLine(), which will consume the newline character (but now the two characters were already consumed by next(), so the resulting string is empty). Calling .charAt(1) on the empty string generates the exception because there is no position (1) in the empty string (it's length is 0).
Instead I'd suggest you use something like this:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String majorAndClassification = "";
while( majorAndClassification.length() != 2 )
majorAndClassification = input.nextLine();
char ch = majorAndClassification.charAt(0);
char ch1 = majorAndClassification.charAt(1);
This will make sure that the user enters two characters - if he doesn't, he'll have to try again until he does. A slightly better option would of course be to print out the prompt every time, like so:
//Step 2: Ask user to enter two characters
String majorAndClassification = "";
while( majorAndClassification.length() != 2 ){
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
majorAndClassification = input.nextLine();
}
If you enter the second entered character, it reads out of range because of charAt(1). Just change it to charAt(0), because you alwayws read only the first character of the input:
char ch = input.next().charAt(0);
char ch1 = input.next().charAt(0);
It works for both inputs:
i
3
And also i 3
change your code from char ch1 = input.nextLine().charAt(1);
to this char ch1 = input.next().charAt(0);
you can check this for more details about differences between next() and nextLine()
Calling
final char ch1 = input.nextLine().charAt(1);
expects a whole line to be read, and there getting the second letter.
But
char ch = input.next().charAt(0);
already consumed the first char.
So you should read the whole input in one go, then (do more checking and then) get your chars.
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
final String reply = input.nextLine();
final char ch = reply.charAt(0);
final char ch1 = reply.charAt(1);
//Step 3: Print statement

How to take character input in java

In C, we are able to take input as character with the keyword char from keyboard as
scanf("%c", &ch);
But In Java how to do this?
I have tried this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
char c = scanner.next().charAt(0);
System.out.println("You have entered: "+c);
}
}
you can use a Scanner to read from input :
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
You can simply use (char) System.in.read(); casting to char is necessary to convert int to char
import java.util.Scanner;
class SwiCas {
public static void main(String as[]) {
Scanner s= new Scanner(System.in);
char a=s.next().charAt(0);//this line shows how to take character input in java
switch(a) {
case 'a':
System.out.println("Vowel....");
break;
case 'e':
System.out.println("Vowel....");
break;
case 'i':
System.out.println("Vowel....");
break;
case 'o':
System.out.println("Vowel....");
break;
case 'u':
System.out.println("Vowel....");
break;
case 'A':
System.out.println("Vowel....");
break;
case 'E':
System.out.println("Vowel....");
break;
case 'I':
System.out.println("Vowel....");
break;
case 'O':
System.out.println("Vowel....");
break;
case 'U':
System.out.println("Vowel....");
break;
default:
System.out.println("Consonants....");
}
}
}
use the System class
char yourChar = System.in.read()
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
using java you can do this:
Using the Scanner:
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
Using the BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
In the two cases you need to pass you Default input, in my case System.in
use :
char ch=**scanner.nextChar**()
I had the same struggle and I this is what I used:
} public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();
char symbolChar = symbol.charAt(0);
This works just fine.
The idea is to get from the string the only char in it.
import java.util.Scanner;
class CheckVowel {
public static void main(String args[]) {
Scanner obj= new Scanner(System.in);
char a=obj.next().charAt(0);
switch(a) {
case 'a': //cases can be used together for the same statement
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
{
System.out.println("Vowel....");
break;
}
default:
System.out.println("Consonants....");
}
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a character:");
String str = next();
char c = str.charAt(0);
System.out.println(c);
sc.close();
}
[Output of this program.][1]}

Categories

Resources