Java: why is this code not working? Infinite loop? - java

So as you may be able to tell from my attempt, I'm trying to figure out how I'd make a program which gives the user 5 seconds to enter some lines of text, then the Scanner will count how many lines were entered. I've just started learning Java as my 2nd language, so please try to explain everything as simply as possible :)
I've got two theories as to why it's not working. The first is that nextLine() will return the whole line, regardless of whether it's empty or not meaning rather than NL equaling "", it will actually equal the whole line (ie " "). And my second theory is that I've got no idea what I'm doing and the program flow is all over the place. Anyway, here's my code:
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
String NL = ScanObj.nextLine();
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (!NL.equals("")){
Count++;
NL = ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
Oh, I forgot to mention hasNext() was what I originally tried:
import java.util.Scanner;
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (ScanObj.hasNext() == true){
Count++;
ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}

From the looks of it, this code should work. My only guess is that you are manually entering the input and are forgetting to signal the end of input with CTRL+D. However, doing this, you'll get a NoSuchElementException if you do not use ScanObj.hasNext().
You could also run your code using input redirection. java OrigClass < data
A better way to do this would be the following:
import java.util.Scanner;
public class Sc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
String nl; // = scan.nextLine();
//while (!NL.equals(""))
while(scan.hasNext())
{
count++;
nl = scan.nextLine();
}
System.out.println("Done! Count: " + count);
scan.close();
}
}
The difference here is that we save the first nextLine() until we're in the while loop. This will give an accurate count of how many lines are in the input.
Just don't forget to signal end of input with CTRL+D.

Well this solution is not really good. but works.
public class FiveSecond {
public static void main(String args[]){
new Thread(new Count(new Reader())).start();
}
}
class Count implements Runnable{
Reader r;Thread t;
Robot ro;
public Count(Reader t){this.r=t;
try {
ro=new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
#Override
public void run() {
t=new Thread(r);
//t.setDaemon(true); //[S2]
t.start();
try{
Thread.sleep(5000);
}catch(Exception e){}
t.interrupt();
//Implicitly press the enter key in order to release the readLine() method :D
//not recommended, and it's not a good idea, but works
ro.keyPress(KeyEvent.VK_ENTER);
ro.keyRelease(KeyEvent.VK_ENTER);
/*
* this is possible to save the strings lines in somewhere in order to access from invoker application
* or send back the strings by socket, etc . . .
*/
System.out.println("number of entered lines "+r.getCount()+"\n");
//you would run this main as a process and get the number of counts
//System.exit(r.getCount()); //[S2]
}
}
class Reader implements Runnable{
private List<String> lines;
private volatile int count;
private BufferedReader br;
public Reader(){
lines=new ArrayList<String>();
br=new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
try{String line;
System.out.println("you have 5 second to detect a 2048 length character, then your system will broken");
while((line=br.readLine())!=null){
if(!Thread.currentThread().isInterrupted()){
count++;lines.add(line);}else{break;}
}
//for showing the lines entered
//System.out.println(lines.toString());
}catch(Exception ex){}
}
public int getCount(){return this.count;}
}
but the best approach is about running a separated process to count the lines, and you would just remove the [S2] comments to achieve it.

Related

The Command Prompt just hangs after executing my java program

It seems like there is no problem with this code (here it is):
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput = new Scanner(System.in);
static int guessedNumber = userInput.nextInt();
public static void main(String[] args) {
start: {
while (guessedNumber != randomNumber) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
delay(1500);
System.out.print("Try to guess it: ");
if (guessedNumber == randomNumber) {
System.out.print("Congradulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
break start;
}
}
}
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
If you couldn't tell already I'm a beginner trying to create a basic number guessing game. So I successfully coded it but now every time I execute it this happens:
It just freezes. Why?
The issue is that you're putting the userInput.nextInt() call in the initializer for a static field; so it gets called (and the program pauses for input) as your class is loading, before it can pribt a prompt requesting the input. So it looks like it froze, but if you enter a number it will then proceed.
You want the nextInt() call to be inside your method after the calls that prompt for input
The error is because your program is waiting for an user input. According to the docs, a Scanning operation may block waiting for input
The solution is implementing a do/while and userInput and guessedNumber initialized when they are required.
NumberGuessingGame:
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput;
static int guessedNumber;
public static void main(String[] args) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
do
{
delay(1500);
System.out.print("Try to guess it: ");
userInput = new Scanner(System.in);
guessedNumber = userInput.nextInt();
if (guessedNumber == randomNumber) {
System.out.print("Congratulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
System.out.println("Error, try again! ");
delay(800);
}
}
while (guessedNumber != randomNumber);
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
Documentation:
do-while statement
its probably waiting for you to enter a number. I conformed its not hanging. its waiting for user input. try entering a number.

hasNext() function does no terminate while loop

public class EOF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=1;
while(sc.hasNextLine()==true)
{
String str = sc.nextLine();
System.out.println(i+" "+str);
i++;
}
System.out.println("completed");
}
}
The last line System.out.println("completed"); is not executing. The loop does not terminate and is continuously running.
From the documentation for Scanner.hasNextLine():
This method may block while waiting for input.
That means that if there isn't input waiting to be returned, it will sit and wait for more input to come in.
If your Scanner is accepting input from System.in, you need to find a better way of deciding when you want to finish input. For instance, if the user types "quit", or if they input a blank line.
please use this
public class EOF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=1;
while(sc.hasNextLine()==true)
{
String str = sc.nextLine();
System.out.println(i+" "+str);
i++;
if(str.equals("stop")){
break;
}
}
System.out.println("completed");
}
}

Simple Java program that squares and cubes a users input number

I am currently taking my first programming class in college and so far have been very good with understanding how to code basic things. This latest assignment has me confused and stumped.
My assignment is to:
Accept numeric input from the user (integer value)
Print out the square and cube of the number entered.
Make sure that the number is > 0.
Repeat the above three times.
If the number entered is <= 0 then end the program, telling the user why.
My issue is that I am unsure how the variables are to be set for this and how exactly to add the loop to repeat the process 3 times.
This is all I have so far and do not know where to go from here, any help would be appreciated. Thank you
import java.io.*;
public class Assignment3 //class name here, same as file name
{
public Assignment3() throws IOException{ //constructor, place class name here
// use BufferedReader class to input from the keyboard
// declare a variable of type BufferedReader
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//declare variable for input
String inputString;
// houseKeeping()
String yourNumber;
int number;
int totalSquare = 0;
int totalCube = 0;
int count;
int badNumber=0;
String squareCube = " Your number squared is" +square +"your number cubed is"+cube;
System.out.print("Enter a number: ");
inputString = input.readLine();
yourNumber = inputString;
}//end constructor
}
public static void main(String [] args) throws IOException
{
new Assignment3(); //class constructor name
}
I could just post the answer here, but then that wouldn't help you learn :)
Firstly, consider using a Scanner to get your inputs. Using BufferedReader will read input data as String. It is possible to convert String to int using Integer.parseInt() but it's more convenient to use Scanner.nextInt().
Secondly, about looping:
Since you want to loop 3 times, the following form of loop seems appropriate:
for (int i=0; i<3; i++) {
//read input, calculate square & cube
}
Inside the loop, you'll want to check for invalid entry (number <= 0), and if so, use break to jump out of the loop early and end the program.
Sorry for the bad format.. I tried too long to fix it on the site...
package com.ispecsoft.porkypig;
import java.io.*;
public class Assignment3 // class name here, same as file name
{
public Assignment3() throws Exception
{
}
public static void DoIt()
{
try
{
int xIn = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
for (int x = 0; x < 3; x++)
{
System.out.print("Enter a number: ");
xIn = Integer.parseInt(input.readLine());
int iSquare = xIn * xIn;
int iCube = iSquare * xIn;
System.out.println(x == 0 ? " Your number squared is ("+ iSquare + ") your number cubed is (" + iCube: ") Your number squared is (" + iSquare+ ") your number cubed is (" + iCube + ")");
}
}
catch (NumberFormatException e)
{
System.out.print("The character's you entered are not integers.. this application will now close. ");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
System.out.print("There was an IOException.. this application will now close. ");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Assignment3.DoIt();
}
}

Using nextLine() and nextInt() together in my context always gets an error

I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.

How to display asterisk for input in Java? [duplicate]

This question already has answers here:
Masking password input from the console : Java
(5 answers)
Closed 8 years ago.
I need to write a little program in Java that asks a person to enter a Pin Code.
So I need the Pin to be hidden with asterisks (*) instead of the numbers. How can I do that?
So far, this is my code :
import java.util.Scanner;
import java.io.*;
public class codePin {
public static void main(String[] args){
int pinSize = 0;
do{
Scanner pin = new Scanner(System.in);
System.out.println("Enter Pin: ");
int str = pin.nextInt();
String s = new Integer(str).toString();
pinSize = s.length();
if(pinSize != 4){
System.out.println("Your pin must be 4 integers");
} else {
System.out.println("We're checking if Pin was right...");
}
}while(pinSize != 4);
}
}
Actually this program works for now, but I want to add a functionality to display Pin like "* * * " or " * *" etc... (in the console when the Person enters is own Pin).
I found something to entirely hide the Pin, but I do not want this. I want the Pin with asterisks
Any ideas ? Thanks
Something like this:
import java.io.*;
public class Test {
public static void main(final String[] args) {
String password = PasswordField.readPassword("Enter password:");
System.out.println("Password entered was:" + password);
}
}
class PasswordField {
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
et.stopMasking();
return password;
}
}
class EraserThread implements Runnable {
private boolean stop;
public EraserThread(String prompt) {
System.out.print(prompt);
}
public void run () {
while (!stop){
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}
The Console class is the correct way to read passwords from the command line. However, it doesn't print asterisks, as that would leak information in general (not in the case where a PIN is known to be 4 digits). For something like that, you'd might need a curses library.

Categories

Resources