for loop iterated unexpectedly - for-loop

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

Related

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

I am trying to print the method findAverage in the main method, can anyone tell me how to fix

public class Grade {
private int [] array = {2,3,1,4,5,7,1};
public int findSum() {
int sum;
sum = 0;
for(int i =0; i <array.length; i++)
{
sum = sum +array[i];
}
return sum;
}
public double findAverage() {
double average;
average = findSum()/array.length;
return average;
}
}
class ExamClient {
public static void main(String[] args) {
double answer;
answer = findAverage();
System.out.println("Average of all elements in the array is" + answer);
}
}
In the main you have to create a instance of the class
Create instance
public static void main(String[] args)
{
double answer;
Grade g= new Grade();
answer = g.findAverage();
System.out.println("Average of all elements in the array is" + answer);
}
Also you can make the method static

multiple times character entry using bufferedreader in java

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

SimpleTextLoader UDF in Pig

I want to create a Custom Load function for Pig UDF, I have created a SimpleTextLoader using the link
https://pig.apache.org/docs/r0.11.0/udf.html , I have successfully generate the jar file for this code, register in pig and run a Pig Script.I am getting the empty output. I don't know how to solve this issue, any help would be appreciated.
Below is my Java code
public class SimpleTextLoader extends LoadFunc{
protected RecordReader in = null;
private byte fieldDel = '\t';
private ArrayList<Object> mProtoTuple = null;
private TupleFactory mTupleFactory = TupleFactory.getInstance();
private static final int BUFFER_SIZE = 1024;
public SimpleTextLoader() {
}
public SimpleTextLoader(String delimiter)
{
this();
if (delimiter.length() == 1) {
this.fieldDel = (byte)delimiter.charAt(0);
} else if (delimiter.length() > 1 && delimiter.charAt(0) == '\\') {
switch (delimiter.charAt(1)) {
case 't':
this.fieldDel = (byte)'\t';
break;
case 'x':
fieldDel =
Integer.valueOf(delimiter.substring(2), 16).byteValue();
break;
case 'u':
this.fieldDel =
Integer.valueOf(delimiter.substring(2)).byteValue();
break;
default:
throw new RuntimeException("Unknown delimiter " + delimiter);
}
} else {
throw new RuntimeException("PigStorage delimeter must be a single character");
}
}
private void readField(byte[] buf, int start, int end) {
if (mProtoTuple == null) {
mProtoTuple = new ArrayList<Object>();
}
if (start == end) {
// NULL value
mProtoTuple.add(null);
} else {
mProtoTuple.add(new DataByteArray(buf, start, end));
}
} #Override
public Tuple getNext() throws IOException {
try {
boolean notDone = in.nextKeyValue();
if (notDone) {
return null;
}
Text value = (Text) in.getCurrentValue();
System.out.println("printing value" +value);
byte[] buf = value.getBytes();
int len = value.getLength();
int start = 0;
for (int i = 0; i < len; i++) {
if (buf[i] == fieldDel) {
readField(buf, start, i);
start = i + 1;
}
}
// pick up the last field
readField(buf, start, len);
Tuple t = mTupleFactory.newTupleNoCopy(mProtoTuple);
mProtoTuple = null;
System.out.println(t);
return t;
} catch (InterruptedException e) {
int errCode = 6018;
String errMsg = "Error while reading input";
throw new ExecException(errMsg, errCode,
PigException.REMOTE_ENVIRONMENT, e);
}
}
#Override
public void setLocation(String string, Job job) throws IOException {
FileInputFormat.setInputPaths(job,string);
}
#Override
public InputFormat getInputFormat() throws IOException {
return new TextInputFormat();
}
#Override
public void prepareToRead(RecordReader reader, PigSplit ps) throws IOException {
in=reader;
}
}
Below is my Pig Script
REGISTER /home/hadoop/netbeans/sampleloader/dist/sampleloader.jar
a= load '/input.txt' using sampleloader.SimpleTextLoader();
store a into 'output';
You are using sampleloader.SimpleTextLoader() that doesn't do anything as it is just an empty constructor.
Instead use sampleloader.SimpleTextLoader(String delimiter) which is performing the actual operation of split.

Why different result each run?

I'm playing around with CompletableFuture and streams in Java 8 and I get different printouts each time I run this. Just curious, why?
public class DoIt {
public static class My {
private long cur = 0;
public long next() {
return cur++;
}
}
public static long add() {
long sum = 0;
for (long i=0; i<=100;i++) {
sum += i;
}
return sum;
}
public static long getResult(CompletableFuture<Long> f) {
long l = 0;
try {
f.complete(42l);
l = f.get();
System.out.println(l);
} catch (Exception e) {
//...
}
return l;
}
public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(2);
My my = new My();
long sum = Stream.generate(my::next).limit(20000).
map(x -> CompletableFuture.supplyAsync(()-> add(), exec)).
mapToLong(f->getResult(f)).sum();
System.out.println(sum);
exec.shutdown();
}
}
If I skip the f.complete(42l) call I always get the same result.
http://download.java.net/jdk8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-
by the time the complete(42l) call happens, some add()'s may have already completed.

Resources