multiple times character entry using bufferedreader in java - bufferedreader

I am trying to enter a letter and a number. 1st input going fine but 2nd input its not taking rather going to the end of line stating not a digit. Please help.
public class charString {
public static void main(String args[]) throws IOException {
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
System.out.print("Enter a character: ");
char p=(char)(in.read());
if(Character.isLetter(p))
System.out.println(p+" is a letter");
else
System.out.println(p+" is not a letter");
System.out.print("Enter a character: ");
char p1=(char)(in.read());
if(Character.isDigit(p))
System.out.println(p1+" is a digit");
else
System.out.println(p1+" is not a digit");
}
}

try this
public static void main(String args[]) throws IOException {
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
System.out.print("Enter a character: ");
String character = in.next();
char p = character.charAt(0);
characterChecker(p);
}
private void characterChecker(Char p) {
if(Character.isLetter(p)) {
System.out.println(p+" is a letter");
} else if (Character.isDigit(p)) {
System.out.println(p1+" is a digit");
}
}
EDIT You can also check out
Character.isLetterOrDigit(charAt(p))
hope this helps ..

Related

for loop iterated unexpectedly

I am a newbie to Java programming and is trying to self-learn the language. I want to create a program that will terminate when a 's' is typed, but what confuse me is my for loop is iterated twice after a letter is entered?
My code:
public class Demo {
public static void main(String[] args)
throws java.io.IOException{
int i;
System.out.println("Press s to stop: ");
for(i = 0; (char) System.in.read() != 's'; i++)
{
System.out.println("Pass #"+i);
}
}
My result:
How should I solve this problem?
Well it is because when you press the enter key the \n also gets into the inputstream.
Thus one iteration is for the letter the other for the \n character.
A Solution would be:
public class Demo {
public static void main(String[] args)
throws java.io.IOException{
int i;
System.out.println("Press s to stop: ");
char c = System.in.read();
for(i = 0; c != 's'; i++)
{
if(c == '\n') continue;
System.out.println("Pass #"+i);
c= System.in.read();
}
}

Java console: readPassord()- size/length of the password

Am trying to understand java console class and it's readPassword method. Following is the code i have,
package com.files;
import java.io.Console;
public class NewConsole {
public static void main(String[] args) {
Console c = System.console();
char[] pw=new char[2];
pw = c.readPassword("%s", "pw: ");
System.out.println(pw);
}
}
pw is char array of size 2. But when executing the above program if i enter pw as "abcd" in cmd(> than the array size of pw) it works fine. Why is it not throwing index out bound of exception as the size of input exceeds the size of pw?.
watch below code that you can figure out whats going on here you are assigning new char sequence to pw[]
import java.io.Console;
public class NewConsole {
public static void main(String[] args) {
Console c = System.console();
char[] pw=new char[2];
char [] nw = "hello".toCharArray();
System.out.println(pw.length);
pw = nw;
System.out.println(pw.length);
}
}
and also if you want to throw ArrayIndexOutOfBoundsException then try
import java.io.Console;
public class NewConsole {
public static void main(String[] args) {
Console c = System.console();
char[] pw=new char[2];
char [] str = c.readPassword("%s", "pw: ");
for(int i=0;i<str.length;i++)
pw [i] = str[i];
System.out.println(pw);
}
}
;-) if you find whats going on then please close question

Disk full while running hadoop

I ran a recursive map/reduce program. Something went wrong and it nearly consumes all the disk space available in C drive. So i closed the resource manager, node manager, Name Node, data node consoles.
Now i have a C drive which is almost full and i don't know how to empty the disk space and make my C drive as it was before. What should i do now. Any help is appreciated.
Here is the code
public class apriori {
public static class CandidateGenMap extends Mapper<LongWritable, Text, Text, Text>
{
private Text word = new Text();
private Text count = new Text();
private int Support = 5;
public void CandidatesGenRecursion(Vector<String> in, Vector<String> out,
int length, int level, int start,
Context context) throws IOException {
int i,size;
for(i=start;i<length;i++) {
if(level==0){
out.add(in.get(i));
} else {
out.add(in.get(i));
int init=1;
StringBuffer current = new StringBuffer();
for(String s:out)
{
if(init==1){
current.append(s);
init=0;
} else {
current.append(" ");
current.append(s);
}
}
word.set(current.toString());
count.set(Integer.toString(1));
try {
context.write(word, count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i < length-1) {
CandidatesGenRecursion(in, out, length,level+1,i+1, context);
}
size = out.size();
if(size>0){
out.remove(size-1);
}
}
}
#Override
public void map(LongWritable key,Text value,Context context) throws IOException
{
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
String[] token=new String[2];
int i=0;
while(tokenizer.hasMoreTokens()){
token[i]= tokenizer.nextToken();
++i;
}
StringTokenizer urlToken = new StringTokenizer(token[1],",");
Vector<String> lst = new Vector<String>();
int loop=0;
while (urlToken.hasMoreTokens()) {
String str = urlToken.nextToken();
lst.add(str);
loop++;
}
Vector<String> combinations = new Vector<String>();
if(!lst.isEmpty()) {
CandidatesGenRecursion(lst, combinations, loop,0,0, context);
}
}
}
public static class CandidateGenReduce extends Reducer<Text, IntWritable, Text, IntWritable>
{
public void reduce(Text key,Iterator<IntWritable> values,Context context) throws IOException
{
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
try {
context.write(key, new IntWritable(sum));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception
{
Date dt;
long start,end; // Start and end time
//Start Timer
dt = new Date();
start = dt.getTime();
Configuration conf1 = new Configuration();
System.out.println("Starting Job2");
Job job2 = new Job(conf1, "apriori candidate gen");
job2.setJarByClass(apriori.class);
job2.setMapperClass(CandidateGenMap.class);
job2.setCombinerClass(CandidateGenReduce.class); //
job2.setReducerClass(CandidateGenReduce.class);
job2.setMapOutputKeyClass(Text.class);
job2.setMapOutputValueClass(Text.class);
job2.setOutputKeyClass(Text.class);
job2.setOutputValueClass(IntWritable.class);
job2.setInputFormatClass(TextInputFormat.class);
job2.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job2, new Path(args[0]));
FileOutputFormat.setOutputPath(job2, new Path(args[1]));
job2.waitForCompletion(true);
//End Timer
dt = new Date();
end = dt.getTime();
}
}
Hadoop needs sufficient disk space for its i/0 operations at each phase (map, reduce etc).
Check in your HDFS your job output path and delete the contents.
List contents:
$ sudo -u hdfs hadoop fs -ls [YourJobOutputPath]
Disk used:
$ sudo -u hdfs hadoop fs -du -h [YourJobOutputPath]
Delete contents (be careful!, it's recursive):
$ sudo -u hdfs hadoop fs -rm -R [YourJobOutputPath]
Deleting the output directory might help in freeing your disk from the files created by the MapReduce job.

Accesing file in Mapper through Distributed Cache

I want to access the contents of the distributed file in my Mapper. Below is the code I have written which generates the name of the file for Distributed Cache. Please help me accessing the contents of the file
public class DistCacheExampleMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text >
{
Text a = new Text();
Path[] dates = new Path[0];
public void configure(JobConf conf) {
try {
dates = DistributedCache.getLocalCacheFiles(conf);
String astr = dates.toString();
a = new Text(astr);
} catch (IOException ioe) {
System.err.println("Caught exception while getting cached files: " +
StringUtils.stringifyException(ioe));
}
}
#Override
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output,
Reporter reporter) throws IOException {
String line = value.toString();
for(Path cacheFile: dates){
output.collect(new Text(line), new Text(cacheFile.getName()));
}
}
}
Try this instead in your configure() method:
List<String []> lines;
Path[] files = new Path[0];
public void configure(JobConf conf) {
lines = new ArrayList<>();
BufferedReader SW;
try {
files = DistributedCache.getLocalCacheFiles(conf);
SW = new BufferedReader(new FileReader(files[0].toString()));
String line;
while ((line = SW.readLine()) != null) {
lines.add(line.split(",")); //now, each lines entry is a String array, with each element being a column
}
SW.close();
} catch (IOException ioe) {
System.err.println("Caught exception while getting cached files: " +
StringUtils.stringifyException(ioe));
}
}
This way, you will have the contents of the files (in this case the first file) in the Distributed Cache, in the variable lines. Each lines entry represent a String array, which is split by ','. So the first column of the first row is lines.get(0)[0], the third row of the second line is lines.get(1)[2], etc.

IO streams to JPanel, GUI with InputStream and OutputStream in a JPanels JTextField and JTextArea

I'm trying to write a GUI where the user sees the System output in a JTextArea and where he writes the input in a JTextField, both object inside a JPanel.
How do I do to connect the System output stream to the JTextArea and the System input stream to the JTextField? I have googled and searched these forums but havnt found the solution. I would be very happy if someone could help me with this.
I have a Master class that calls the JPanel with the GUI, and I will have work executed in different threads later on, but right now I struggle with the basic issue of connecting IO streams to the JPanel. Down below is the 2 classes:
public class MainTest {
public static void main(String[] args) throws IOException {
JPanelOUT testpanel = new JPanelOUT();
JFrame frame = new JFrame();
frame.add(testpanel);
frame.setVisible(true);
frame.pack();
/*
System.setOut(CONVERT TEXTAREA TO AN OUTPUTSTREAM SOMEHOW??(JPanelOUT.textArea)));
System.setIn(CONVERT STRING TO AN INPUTSTREAM SOMEHOW?? JPanelOUT.textField);
*/
String text = Sreadinput();
System.out.println(text);
}
public static String Sreadinput() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(JPanelOUT.is));
String input=in.readLine();
return input;
}
}
public class JPanelOUT extends JPanel implements ActionListener {
protected static JTextField textField;
protected static JTextArea textArea;
public static InputStream is;
private final static String newline = "\n";
public JPanelOUT() throws UnsupportedEncodingException, FileNotFoundException {
super(new GridBagLayout());
JLabel label1 = new JLabel("OUTPUT:");;
JLabel label2 = new JLabel("INPUT:");;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
textArea.setBackground(Color.black);
textArea.setForeground(Color.white);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,200));
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(label1, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
add(label2, c);
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
String WelcomeText1 = "Hello and welcome to the TEST";
String WelcomeText2 = "Trying to get the input field below to become the System.in and this output";
String WelcomeText3 = "field to become the System.out (preferrably both with UTF-8 encoding where";
String WelcomeText4 = "the scrollpane automatically scrolls down to the last output line)!";
textArea.append(WelcomeText1 + newline + newline + WelcomeText2 + newline + WelcomeText3 + newline + WelcomeText4 + newline + newline);
String text = textField.getText();
is =new ByteArrayInputStream(text.getBytes("UTF-8"));
}
public void actionPerformed(ActionEvent evt) {
String text2 = textField.getText();
textArea.append(text2 + newline);
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
i am new to java, trying to deal with the streams, too :)
Sorry for bad English I am from Russia.
May be this code will help you.
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public MyPrintStream myPrintStream;
public NewJFrame()throws FileNotFoundException{
initComponents();
this.myPrintStream = new MyPrintStream("string");
}
private class MyPrintStream extends PrintStream {
MyPrintStream(String str)throws FileNotFoundException{
super(str);
}
public void println(String s){
textArea1.append(s+'\n');
}
} .. continuation class code
Main method:
public static void main(String args[]){
/* Set the Nimbus look and feel... */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
try{
NewJFrame myJFrame = new NewJFrame();
myJFrame.setVisible(true);
System.setOut(myJFrame.myPrintStream);
System.out.println("its work");
System.out.println("its work2");
System.out.print("str"); //does not work, need to override
}catch (FileNotFoundException e){System.out.println (e.getMessage());}
}
});

Resources