hey im trying to make a program that if you use a scanner class you can type A and then the switch statment will change that to something else.

altho i just realised that i cant do this as the way i would read a letter into a scanner would be by using this

Scanner scan = new Scanner (System.in);
System.out.print ("please eneter a letter: ");
 value = scan.nextLine();

but the switch class does not let u use strings can anyone lend a hand how i can get around this

thanks for any help

ok just thought could i not read the string in using the scanner class and then convert the string to an int

so A would = 1

and that could then run my switch statement

switch (value)
      {
          case 1:
              System.out.print ("one");
              break;

Recommended Answers

All 5 Replies

Since the switch can only use char or integer, you have two solution:
Parse what you are reading to an integer or a char:
Integer.parseInt(input); for integers or for chars:

if (input.length()==1) char ch=input.charAt(0);
  else {//error}

Make sure that you entering valid values ( use try {}catch() {} )

Or use if () {} else if () {} statements instead of switch with input.equals("") inside the if( )

is there a better way i could read stuff in withour using the scanner class ?

This is the one I use

BufferedReader USERIN = new BufferedReader (new InputStreamReader(System.in));
String s=USERIN.readLine();

There is a plenny ways you can do it, one closer for what you request it's this one:

Scanner s = new Scanner( System.in );
int n = s.nextInt();

Other way:

int n = Integer.parseInt( request.getParameter( "number" ) );

Got the solution of your problem...
Check this code:

import java.io.*;
import java.util.Scanner;
      public class Scan {
          public static void main(String[] args) throws IOException{
              int value;
              System.out.println("Enter any number");
              Scanner scan= new Scanner(System.in);
              value=scan.nextInt();
              switch(value){
                  case 1:System.out.println("One");
                         break;
                  default:System.out.println("Enter another one");
              }

          }

      }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.