How do I use a Scanner method to read a character? I know how to use scan.nextInt to read an integer and scan.nextLine() etc, but what if I only want the user to enter a single character?
This is the static archive of the Massassi Forums. The forums are
closed indefinitely. Thanks for all the memories!
You can also download
Super Old Archived Message Boards
from when Massassi first started.
"View" counts are as of the day the forums were archived, and will no longer increase.
using System.IO public void Func() { using (TextReader tr = new StreamReader(@"c:\temp\text.txt") { int wChar; do { wChar=tr.Read(); Console.Write(string.Format(" {0} ",Convert.ToChar(wChar))); } while (wChar != -1) } }
import java.io.*; import java.util.*; class Test { public static void main(String[]args) { try { Scanner s=new Scanner(new File(args[0])); System.out.printf("%c%n",s.nextLine().charAt(0)); } catch(FileNotFoundException e) { System.err.printf("File not found, lol.%n"); System.exit(-1); } catch(NoSuchElementException e) { System.err.printf("File is empty, lol.%n"); System.exit(-1); } } }
Scanner scan = new Scanner(whatever_you're_scanning_from); Char ch; String line = scan.nextLine(); if(line.length() != 1) { // If you want to give an error for having more than one char, put that code here } else ch = line.charAt(0);