How to take character input in java - 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]}

Related

How to do a switch menu in java with do while

Good day!
This is my switch menu for a project in java!
When I put a diferent letter (letter that it´s not in the switch) I get this error message, and when I try one of the correct letter I get the same error message again:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at teste.menu(teste.java:65)
at teste.main(teste.java:16)
This is my code:
import java.util.Scanner;
public class teste{
public static void main(String[] args){
char ch;
do {
ch = menu();
switch (ch){
case 'a':
//String name ="resultado.csv";
//ReadFile(name);
break;
case 'b':
//WriteFile();
break;
case 'c':
System.out.println("nome");
break;
case 'd':
System.out.println("nome");
break;
case 'e':
System.out.println("nome");
break;
case 'f':
System.out.println("nome");
break;
case 'g':
System.out.println("nome");
break;
case 'h':
System.out.println("nome");
break;
default:
System.out.println("a-k!");
break;
}
}while (ch != 'k');
System.exit(0);
}
public static char menu(){
System.out.println("Chose: ");
System.out.println("a: Show");
System.out.println("b: Write");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("g: Display");
System.out.println("h: Display");
System.out.println("k: Quit");
System.out.println("Insira a opção: ");
Scanner input = new Scanner(System.in);
char ch = input.next().charAt(0);
input.close();
return ch;
}
}
I tryed with numbers and I got the same error message
Don't recreate the scanner each time menu is called. Create it once at start of main and use it, such as:
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// same code...until end of main...
input.close();
System.exit(0);
}
and in menu:
public static char menu() {
// same prompts...
//REMOVE Scanner input = new Scanner(System.in);
char ch = input.next().charAt(0);
//REMOVE input.close();
return ch;
}

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(' ');
}
}
}

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

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
}
}

Validate the input using a while loop

I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}

No such element exception

The ch variable is not recognised by the while loop although it is declared outside the loop. Why? There is no compilation error.
package calculator;
import java.util.Scanner;
public class Calculation {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1: {
}
.....
default: {
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}
} while (ch != 9);
s.close();
}
}
put your break statement of default case outside the braces. I think that is your problem. I tried the below code and gives me the output.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}while(ch!=9);
s.close();
}
}
This code is working fine. elements of parent block are always visible.
Don't use break in default case
Your code :
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
}
} while (ch != 9);
s.close();
}
}
*Only the edit I made was I removed break from default block.
Running Example :
ENTER YOUR CHOICE : 1
one
ENTER YOUR CHOICE : 2
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 3
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 9
!!!ENTER VALID CHOICE !!!

Categories

Resources