public class pattern7 {
public static void main(String args[])
throws java.io.IOException{
char c;
do
{
System.out.print("*");
System.out.println("\ndo you want more");
c=(char)System.in.read();
}while(c=='y');
}
}
the above code should print the * as long as i press 'y' but it does not do so. it let the user to enter choice just once. i know the reason behind this as it uses "enter" as its second value. but i don't know how to make it work. suggest me the code to do the same action properly
it takes enter key press as a new character. So capture that key press add another read command.
do
{
System.out.print("*");
System.out.println("\ndo you want more");
do {
c=(char)System.in.read();
} while (Character.isWhitespace(c));
} while (c=='y');
If the 'y' character will always be followed by an enter, just always read the full line and check if it only contains the 'y' character:
Option 1: BufferedReader
You can use InputStreamReader in combination with BufferedReader to get the full line the user entered. After that, you check that it is not null and only contains 'y'.
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null && line.equals("y") ) {
System.out.print("*");
System.out.println("\ndo you want more?");
}
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Option 2: Scanner
The same as above can be achieved by using the java.util.Scanner class:
Scanner scan = new Scanner(System.in);
scan.nextLine(); // reads a line from the console. Can be used instead of br.readLine();
You can do this by using Scanner. Here is my code-
public class pattern7 {
public static void main(String args[])
throws java.io.IOException{
char c;
Scanner reader = new Scanner(System.in);
do
{
System.out.print("*");
System.out.println("\ndo you want more");
c=reader.next().charAt(0);
}while(c=='y');
}
}
Related
I am currently having a problem with my loop. After I inputted a string once, it prompts the user and when the loop conditions were met, it just keeps asking the user "do you want to continue?" and was unable to enter another string.
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
LinkedList<String> strList = new LinkedList();
char choice;
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
choice = (char)bfr.read();
}
while(choice == 'Y');
}
You need to get the newline character out of the keyboard buffer. You can do this like this:
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
//choice = (char)bfr.read();
choice = bfr.readLine().charAt(0); // you might want to check that a character actually has been entered. If no Y or N has been entered, you will get an IndexOutOfBoundsException
}
while(choice == 'Y');
Usually the terminal only sends the data once you hit enter. So you get an empty line when you perform readLine again. You have to read a line, then check if it contains Y instead. Or read the empty line afterwards, whichever you think is less error prone.
I tend to use the earlier and read a full line, then check what it contains.
Don't forget that for something simple as this program you can use the convenient java.io.Console class.
Console console = System.console();
LinkedList<String> list = new LinkedList<>();
char choice = 'N';
do {
System.out.print("Add Content: ");
list.add(console.readLine());
System.out.print("Do you want to add again? Y/N?\n");
choice = console.readLine().charAt(0);
} while (choice == 'Y' || choice == 'y');
This work (don't forget library):
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
List<String> strList = new ArrayList<String>();
String choice;
do {
System.out.println("Add Content: ");
strList.add(bfr.readLine());
System.out.println("Do you want to add again? Y/N?");
choice = bfr.readLine();
} while(choice.equals("Y"));
System.out.println("End.");
}
Try this :
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
LinkedList<String> strList = new LinkedList();
String choice;`
do
{
System.out.print("Add Content: ");
strList.add(scan.nextLine());
System.out.print("Do you want to add again? Y/N?");
choice = scan.nextLine();
}
while(choice.equals("Y"));
}
I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)
Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}
I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.
You could use the empty line as a loop-breaker:
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}
You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content:
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);
if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}
}
}
You can use this code. It returns when the user press Enter on an empty line.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> arrayLines = new ArrayList<>();
String line;
while(true){
line = scanner.nextLine();
if(line.equals("")){
break;
}
else {
System.out.println(line);
arrayLines.add(line);
}
}
System.out.println(arrayLines);
}
}
Best
You can do somthing like this:
while (s.hasNextLine() == true){
String line = s.nextLine();
if ("".equals(line)) {
break;
}
in.add(line);
//infinite loop
}
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.
public class Main {
public static void main(String[] args)
{
int ch = 0;
do
{
Scanner in = new Scanner(System.in);
String s;
System.out.println("Enter the part number");
s=in.nextLine();
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number.txt"));
BufferedReader Br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number1.txt"));
String strLine;
int flag=0;
while ((strLine = br.readLine()) != null)
{
if(strLine.equals(s))
{
flag=1;
System.out.println ("Part Number exists in 1");
break;
}
else
{
flag=0;
System.out.println ("Part Number doesnot exist in 1");
break;
}
}
if(flag==0)
{
while ((strLine = Br.readLine()) != null)
{
if(strLine.equals(s))
{
System.out.println ("Part Number exists in 2");
break;
}
else
{
System.out.println("File does not exist in 2");
break;
}
}
}
System.out.println ("Do you want to continue-Press1 for yes and 2 for no");
ch= in.nextInt();
br.close();
Br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
while(ch==1);
}
}
this is the program that I made to search a user given string from 2 diff text files. Its working fine but only searching the first line.
eg.: If a file has
1000
1001
1002
it wll only search 1000. How do I go to next line and keep on using the .equals() method?
You should use Scanner not BufferedReader as it's a more recent class
and I feel does a nicer job with this task. Especially since you have
already used Scanner elsewhere in your code and thus imported it.
Below is a scanner that will read all the lines in a file while there
is a next one to read.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaApplication32
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Scanner scanner1 = null;
Scanner scanner2 = null;
String partCheck;
String repeatLoop;
boolean isInOne;
boolean isInTwo;
File file1 = new File("data1.txt");
File file2 = new File("data2.txt");
try
{
scanner1 = new Scanner(file1);
scanner2 = new Scanner(file2);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
do
{
isInOne = false;
isInTwo = false;
System.out.println("Enter the part number");
partCheck = keyboard.nextLine();
while (scanner1.hasNextLine() && !isInOne)
{
String line = scanner1.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 1");
isInOne = true;
}
}
if(!isInOne)
{
System.out.println("Part Number does not exist in 1");
}
while(scanner2.hasNextLine() && !isInOne && !isInTwo)
{
String line = scanner2.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 2");
isInTwo = true;
}
}
if(!isInTwo)
{
System.out.println("Part Number does not exist in 2");
}
System.out.println("Do you want to continue? (Y/N)");
repeatLoop = keyboard.nextLine();
} while(repeatLoop.equalsIgnoreCase("y"));
scanner1.close();
scanner2.close();
}
}
Example Text File data1.txt:
Test1
Test2
Test3
Test4
Example Test File data2.txt
Check1
Check2
Check3
Check4
Example stdout when code is run with these datafiles:
run:
Enter the part number
Test1
Part Number exists in 1
Part Number does not exist in 2
Do you want to continue? (Y/N)
y
Enter the part number
Check1
Part Number does not exist in 1
Part Number exists in 2
Do you want to continue? (Y/N)
n
BUILD SUCCESSFUL (total time: 19 seconds)
You also shouldn't put all of your read in information in a loop. By
putting do at the top you effectively keep creating a new set of
BufferedReaders and naming them the same thing and telling to do the
same thing and then telling them to break after the first hit. If you
did actually get rid of the break you'd have even more problems since
all of this other stuff is in the loop where it shouldn't be.
Since you have used
break;
in while loop it will exit from the loop after check first line. Try removing break; if you want to read all lines.
I am writing a command line program and would like to make the the user to enters a valid age (integer). By using the Scanner class, I have something like this:
int getAge() {
Scanner = new Scanner(System.in);
int age;
boolean isValid = false;
while(!isValid) {
System.out.println("Please enter your age");
if (myScanner.hasNext()) {
if (myScanner.hasNextInt()) {
age = myScanner.nextInt();
isValid = true;
} else {
System.out.println("Please enter an integer");
}
}
}
return age;
}
The problem being that while in the loop it keeps reading input without waiting for a new value. How can I get around this?
You are not reading any token in your else path thus processing the same input over and over again. Just add the following line
myScanner.next();
inside the else-block.
You could also just use something like this. To read an entire line using a BufferedReader then parse the integer from the string and catch any exception that might occur.
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int intVal;
try {
intVal = Integer.parseInt(s);
}
catch(NumberFormatException nfe) {
//Do Something
}
You could place this inside your loop. (Yes I realize it doesn't use Scanner... just wanted to show an alternate approach.)