Why will this code not print anything to the console? - printing

I am very new to java as I have only started yesterday and I am trying to make a little game where a random number is generated and you have to try to guess that number. The problem I am having right now is nothing will come out of the console. I am not sure what is causing this as it might be the code or the interpreter I am using. Here is the code for you guys to check over. Let me know what I did wrong and if you can find a fix, thanks.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args){}
{System.out.println("Geuss a number and see if it is correct!");
}
{
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
public void If(boolean b) {}
}

you have empty{}
public static void main(String[] args){
System.out.println("Geuss a number and see if it is correct!");
}
Also do not write IF as a function. If is native expression in native coding.
There is already if clause so try to give unique names.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args)
{
System.out.println("Geuss a number and see if it is correct!");
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
}

try this.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args){
System.out.println("Geuss a number and see if it is correct!");
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
public void If(boolean b) {}
}
}

Related

proper video streaming with rxjava

To handle a video stream from a webcam (delivered by opencv) i am considering to use RxJava.
I am hoping to achieve the following:
being able to control the frames per second to be delivered
to be able to handle different inputs - e.g. a life webcam, a video or even a still picture
being able to switch to a picture-by-picture handling under the control of a gui
I have been experimenting a bit with RxJava but i am confused about the debounce, throttleFirst and async operators
Examples like https://stackoverflow.com/a/48723331/1497139 show some code but I am missing more detailed explanation.
Where could I find a decent example for video processing or something similar along the needs mentioned above?
The code below does some non async logic at this time - please let me know if i could build on it:
ImageFetcher
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
/**
* fetcher for Images
*
*/
public class ImageFetcher {
// OpenCV video capture
private VideoCapture capture = new VideoCapture();
private String source;
protected int frameIndex;
public int getFrameIndex() {
return frameIndex;
}
/**
* fetch from the given source
*
* #param source
* - the source to fetch from
*/
public ImageFetcher(String source) {
this.source = source;
}
/**
* try opening my source
*
* #return true if successful
*/
public boolean open() {
boolean ret = this.capture.open(source);
frameIndex=0;
return ret;
}
/**
* fetch an image Matrix
*
* #return - the image fetched
*/
public Mat fetch() {
if (!this.capture.isOpened()) {
boolean ret = this.open();
if (!ret) {
String msg = String.format(
"Trying to fetch image from unopened VideoCapture and open %s failed",
source);
throw new IllegalStateException(msg);
}
}
final Mat frame = new Mat();
this.capture.read(frame);
frameIndex++;
return !frame.empty() ? frame : null;
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
/**
* convert me to an observable
* #return a Mat emitting Observable
*/
public Observable<Mat> toObservable() {
// Resource creation.
Func0<VideoCapture> resourceFactory = () -> {
VideoCapture capture = new VideoCapture();
capture.open(source);
return capture;
};
// Convert to observable.
Func1<VideoCapture, Observable<Mat>> observableFactory = capture -> Observable
.<Mat> create(subscriber -> {
boolean hasNext = true;
while (hasNext) {
final Mat frame = this.fetch();
hasNext = frame!=null && frame.rows()>0 && frame.cols()>0;
if (hasNext) {
String msg = String.format("->%6d:%4dx%d", frameIndex, frame.cols(), frame.rows());
System.out.println(msg);
subscriber.onNext(frame);
}
}
subscriber.onCompleted();
});
// Disposal function.
Action1<VideoCapture> dispose = VideoCapture::release;
return Observable.using(resourceFactory, observableFactory, dispose);
}
}
ImageSubscriber
import org.opencv.core.Mat;
import rx.Subscriber;
public class ImageSubscriber extends Subscriber<Mat> {
public Throwable error;
public int cols = 0;
public int rows=0;
public int frameIndex=0;
public boolean completed = false;
public boolean debug = false;
#Override
public void onCompleted() {
completed = true;
}
#Override
public void onError(Throwable e) {
error = e;
}
#Override
public void onNext(Mat mat) {
cols = mat.cols();
rows = mat.rows();
frameIndex++;
if (cols==0 || rows==0)
System.err.println("invalid frame "+frameIndex);
if (debug) {
String msg = String.format("%6d:%4dx%d", frameIndex, cols, rows);
System.out.println(msg);
}
}
};

Fibonacci sequence, public static void xxx

I'm just a very beginner and need for help with Fibonacci sequence. So the problem is that I need to ask a number from the answerer and secondly print the Fibonacci number that fits with the answerer's number? Is the method that I need to use "public static void xxx" loop?
I hope someone understands my bad English and can help me with my problem.
I hope you need it in java:
import java.io.*;
public class Fibonacci{
// your method public static void xxx
public static void fib() throws IOException
{
// take input from user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
// compute nth fibonacci: your loop
int f1 = 0, f2 = 1;
if(n == 0)
System.out.println(f1);
for(int i=2; i<n; i++)
{
int fi = f1 + f2;
f1 = f2;
f2 = fi;
}
// print your answer
System.out.println(f2);
}
public static void main(Strings args[])
{
// call fib method
fib();
}
}

Why does this priority queue implementation only print one value repeatedly?

This program should print out the values in order ascending order. But it only displays 957.0 repeatedly. How do I display the numbers in order?
import java.io.*;
import java.util.*;
class PriorityQ {
public int maxSize;
public double[] queArray;
public int nItems;
//------
public PriorityQ(int s){
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
//-----
public void insert(double item){
int j;
if(nItems == 0){
queArray[nItems++] = item;
}
else{
for(j = nItems-1; j >= 0; j--){
if(item > queArray[j]){
queArray[j + 1] = item;
}
else{
break;
}
}
queArray[j + 1] = item;
nItems++;
}
}
//-----
public double remove(){
return queArray[--nItems];
}
//-----
public double peekMin(){
return queArray[nItems - 1];
}
//-----
public boolean isEmpty(){
return(nItems == 0);
}
//-----
public boolean isFull(){
return(nItems == maxSize);
}
}
//-----
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(546);
thePQ.insert(687);
thePQ.insert(36);
thePQ.insert(98);
thePQ.insert(957);
while(!thePQ.isEmpty()){
double item = thePQ.remove();
System.out.print(item + " ");
}
System.out.println("");
}
}
You should save yourself the effort and use a priority queue with the generic type Double. If you wanted descending order you could even use a comparator that orders the highest value before the lowest, but you asked for ascending.
Your problem is that your array does contain many copies of 957.
This is because of this line in your code:
if(item > queArray[j]){
queArray[j + 1] = item;
}
Try:
import java.io.*;
import java.util.*;
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQueue<Double> thePQ = new PriorityQueue<Double>(5);
thePQ.add(546);
thePQ.add(687);
thePQ.add(36);
thePQ.add(98);
thePQ.add(957);
while(thePQ.size() > 0){
double item = thePQ.poll();
System.out.print(item + " ");
}
System.out.println("");
}
}
Or I can fix your code to print out the queue in descending order leaving it to you to then make it print out in ascending order, the block I pointed to before should read like this instead:
if(item < queArray[j]){
queArray[j + 1] = queArray[j];
}

Is it bad to use "return" to escape from the main method?

So this might be an exceptionally dumb question, but before you burn this post to smolders, please hear me out XD. Below I've written three basic classes, all of which accomplish the same thing, but through various means:
Class A ( break ) -
import java.util.Scanner;
public class ClassA
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(true)
{
System.out.print("Enter a sentence (/q to quit): ");
String sentence = in.nextLine();
if(sentence.equals("/q"))
break;
else
System.out.println("Thank you!");
}
}
}
Class B ( return ) -
import java.util.Scanner;
public class ClassB
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(true)
{
System.out.print("Enter a sentence (/q to quit): ");
String sentence = in.nextLine();
if(sentence.equals("/q"))
return;
else
System.out.println("Thank you!");
}
}
}
Class C ( System.exit(0) ) -
import java.util.Scanner;
public class ClassC
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(true)
{
System.out.print("Enter a sentence (/q to quit): ");
String sentence = in.nextLine();
if(sentence.equals("/q"))
System.exit(0);
else
System.out.println("Thank you!");
}
}
}
While I prefer Classes A and C, is there anything wrong with B? More specifically, is it bad practice to use a return statement to exit from the main method of a program? If so, why?
Thanks in advance!
Using return is exactly the right thing to do, because it makes your main easier to test -- your test framework doesn't need to intercept exit attempts.

How do I pretty-print productions and line numbers, using ANTLR4?

I'm trying to write a piece of code that will take an ANTLR4 parser and use it to generate ASTs for inputs similar to the ones given by the -tree option on grun (misc.TestRig). However, I'd additionally like for the output to include all the line number/offset information.
For example, instead of printing
(add (int 5) '+' (int 6))
I'd like to get
(add (int 5 [line 3, offset 6:7]) '+' (int 6 [line 3, offset 8:9]) [line 3, offset 5:10])
Or something similar.
There aren't a tremendous number of visitor examples for ANTLR4 yet, but I am pretty sure I can do most of this by copying the default implementation for toStringTree (used by grun). However, I do not see any information about the line numbers or offsets.
I expected to be able to write super simple code like this:
String visit(ParseTree t) {
return "(" + t.productionName + t.visitChildren() + t.lineNumber + ")";
}
but it doesn't seem to be this simple. I'm guessing I should be able to get line number information from the parser, but I haven't figured out how to do so. How can I grab this line number/offset information in my traversal?
To fill in the few blanks in the solution below, I used:
List<String> ruleNames = Arrays.asList(parser.getRuleNames());
parser.setBuildParseTree(true);
ParserRuleContext prc = parser.program();
ParseTree tree = prc;
to get the tree and the ruleNames. program is the name for the top production in my grammar.
The Trees.toStringTree method can be implemented using a ParseTreeListener. The following listener produces exactly the same output as Trees.toStringTree.
public class TreePrinterListener implements ParseTreeListener {
private final List<String> ruleNames;
private final StringBuilder builder = new StringBuilder();
public TreePrinterListener(Parser parser) {
this.ruleNames = Arrays.asList(parser.getRuleNames());
}
public TreePrinterListener(List<String> ruleNames) {
this.ruleNames = ruleNames;
}
#Override
public void visitTerminal(TerminalNode node) {
if (builder.length() > 0) {
builder.append(' ');
}
builder.append(Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false));
}
#Override
public void visitErrorNode(ErrorNode node) {
if (builder.length() > 0) {
builder.append(' ');
}
builder.append(Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false));
}
#Override
public void enterEveryRule(ParserRuleContext ctx) {
if (builder.length() > 0) {
builder.append(' ');
}
if (ctx.getChildCount() > 0) {
builder.append('(');
}
int ruleIndex = ctx.getRuleIndex();
String ruleName;
if (ruleIndex >= 0 && ruleIndex < ruleNames.size()) {
ruleName = ruleNames.get(ruleIndex);
}
else {
ruleName = Integer.toString(ruleIndex);
}
builder.append(ruleName);
}
#Override
public void exitEveryRule(ParserRuleContext ctx) {
if (ctx.getChildCount() > 0) {
builder.append(')');
}
}
#Override
public String toString() {
return builder.toString();
}
}
The class can be used as follows:
List<String> ruleNames = ...;
ParseTree tree = ...;
TreePrinterListener listener = new TreePrinterListener(ruleNames);
ParseTreeWalker.DEFAULT.walk(listener, tree);
String formatted = listener.toString();
The class can be modified to produce the information in your output by updating the exitEveryRule method:
#Override
public void exitEveryRule(ParserRuleContext ctx) {
if (ctx.getChildCount() > 0) {
Token positionToken = ctx.getStart();
if (positionToken != null) {
builder.append(" [line ");
builder.append(positionToken.getLine());
builder.append(", offset ");
builder.append(positionToken.getStartIndex());
builder.append(':');
builder.append(positionToken.getStopIndex());
builder.append("])");
}
else {
builder.append(')');
}
}
}

Resources