Java Continuous Input Code - java

Okay, so the program that I'm trying to figure out how to code (not really fix), I have to use Java to accept continuous input from the user until they enter a period. It then must calculate the total characters that the user input up to the period.
import java.io.*;
class ContinuousInput
{
public static void main(String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inputValues;
int numberValue;
System.out.println("Welcome to the input calculator!");
System.out.println("Please input anything you wish: ");
inputValues = userInput.readLine();
while (inputValues != null && inputValues.indexOf('.')) {
inputValues = userInput.readLine();
}
numberValue = inputValues.length();
System.out.println("The total number of characters is " + numberValue + ".");
System.out.println("Thank you for using the input calculator!");
}
}
Please don't suggest the use of Scanner, the Java SE Platform we're stuck using is the SDK 1.4.2_19 model and we can't update it.
Explanation of empty braces: I thought that if I put in the empty braces that it would allow for continuous input until the period was put in, but clearly that wasn't the case...
Edit: Updated code
Current Error: won't end when . is inputted.

You have to switch the if/else statement with while.
Sample :
inputValues = userInput.readLine();
while (!".".equals(inputValues) {
//do your stuff
//..and after done, read the next line of the user input.
inputValues = userInput.readLine();
}
Note: Never compare the values of String objects with the == operator. Use the equals() method.
If you just want to test, whether the sentence the user inputs contains a . symbols, you just have to switch from equals() to contains(). It's a built-in method from the java.lang.String class.
Sample:
while (inputValues != null && !inputValues.contains(".")) {
//do your stuff
}

Related

Pig latin Java program with try-catch, translation passed though function

I am making a java program that translates a sentence to pig latin. I need to have at least one try-catch in this program and the translation must be done in a function. The original word will be passed to this function and return the translated word back to the function call per my professor's wishes. I am also having trouble asking the user if they want to translate something else. even when I say no it still restarts the program.
this is what I have:
package midtermPigLatin;
import java.util.Scanner;
import textio.TextIO;
public class midtermPigLatin {
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
String yourSentence="";
boolean again = true;
try {
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words)
{
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
System.out.println("Do you want to play again, Yes or no");
again = TextIO.getBoolean();
} while(!yourSentence.equals("quit"));
}catch(Exception errMsg)
{
System.out.print(" error" + errMsg);
}
}
}
I just need help modifying my program to pass the translation through a function original word will be passed to this function and return the translated word back to the function call and the ending the program if user says no.
Here is what I get when I run the program:
Enter your words here: apple door shave
appleway oorday aveshay
Do you want to play again, Yes or no
no
Enter your words here:

Java: Read input without knowing number of input lines

This might be very very basic or may be something I am totally missing. I have started doing some competitive programming on online channels. I have to read comma separated strings and do some manipulations around it but the problem is that I do not know the number of lines of input. Below is the input example
Input 1
John,Jacob
Lesley,Lewis
Remo,Tina
Brute,Force
Input 2
Hello,World
Java,Coder
........
........
//more input lines
Alex,Raley
Michael,Ryan
I am trying to read input and breaking when end of the line is encountered but with no luck. This is what I have been trying
//1st method
Scanner in = new Scanner(System.in);
do{
String relation = in.nextLine();
//do some manipulation
System.out.println(relation);
}while(in.nextLine().equals("")); //reads only first line and breaks
//2nd method
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String relation = in.next();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
//3rd method
Scanner in = new Scanner(System.in);
while(true){ //infinite loop
String relation = in.nextLine();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
Can somebody help here.
PS: Please don't judge. I am new to competitive programming though I know how to take user input in java and difference between next() and nextLine().
Im not gonna write why you shouldn't use Scanner. There are numerous articles why you shouldn't use Scanner in competitive programming. Instead use BufferedReader.
In competitive programming they redirect the input to your code from file.
It works like ./a.out > output.txt < input.txt for example.
So read until null is detected in the while loop.
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null)
{
//System.out.println(s);
}
}
For testing through your keyboard, to simulate a null from your keyboard:
Press Ctrl+D. It will break out of the while loop above.
It should be fairly easy. Try
while(in.hasNextLine()){
String relation = in.nextLine();
if("exit".equalsIgnoreCase(relation))break;
//do some manipulation
System.out.println(relation);
}
The method Scanner#hasNextLine simply checks if there is a next line in the input, doesn't really advance the scanner. On the other hand, Scanner#nextLine reads the input as well as advances the scanner.
Update you might want to put some condition to exit the loop. E.g. the above snippet stops reading more input after it encounters a string "exit".
All your methods can be improved.
But let's consider your second method of while loop.
Scanner in = new Scanner(System.in);
String s;
while(in.hasNext()){
s=in.nextLine();
System.out.println(s);
}
In the same way, you can change each of your codes.
Also you can use BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); to buffer your input then check for in.readLine()) != null
Other than the above two methods (Buffered Reader method & Scanner method), I have another method for solving this issue. Have a look at the following code, you can catch NoSuchElementException to solve this issue , though I didn't recommended this as Exception handling is a costly process .
Out of all the methods, the Buffered should only be used during Competitive Coding as it has the least Complexity.
import java.util.*;
public class Program
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
try
{
while(true)
String a=sc.next();
System.out.print(a);
}
catch(NoSuchElementException k)
{
}
}
}

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

When I run this code it is not allowing me to input to my scanner. Am I using the Scanner properly?

When I run the code I am not able to input to the scanner and continue through the code the way I want to. Can someone help me with some advice? I have imported the java.util.Scanner succesfully. BTW, I do call the method in the original program, I just removed it before I posted the question. I am using BlueJ.
public class Instructions extends ConsoleProgram
{
public boolean question(String prompt) {
Scanner s = new Scanner(System.in);
println(prompt);
String str = s.next();
boolean result = true;
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
if (str.equals("yes")) {
result = true;
} else if (str.equals("no")) {
result = false;
}
return result;
}
Am I using the Scanner properly?
That isn't the problem. The real problem is a straight-forward bug in your application logic. This condition:
!(str.equals("yes") && str.equals("no"))
can never be false. A String cannot be both equal to "yes" AND equal to "no" at the same time. Therefore your while loop cannot terminate.
UPDATE
Following the edit, your code should more or less work. But this is not quite right.
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
1) You are reading the next input token BEFORE you prompt for it.
2) You are not consuming the remaining characters after the first token of the line that the user just entered.
This is better
while(!(str.equals("yes") || str.equals("no"))) {
s.nextLine();
println("enter yes or no");
str = s.next();
}
I suggest you go back and read the javadocs for the Scanner class carefully.
It is also possible that new Scanner(System.in) is wrong. That is normally the right thing to do, but your requirements might require you to read use input from some other input stream.

some logical error in taking up character in java

This is my code...
class info{
public static void main (String[]args) throws IOException{
char gen;
while(true) { //problem occurs with this while
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen=(char)System.in.read();
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
}
System.out.println("\nGENDER = "+gen);
}
}
This is my output...
ENTER YOUR GENDER (M/F) : h
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) : m
GENDER = m
Could someone please help me understand why it is asking for the gender so many times.
You are probably workin' on Windows. When you give an answer and hit enter it adds two extra characters '\r' and '\n'. From stdin you receive only one character but those extra two remain in the buffer. When you give an incorrect answer you loop and automatically read from the buffer those two characters. They don't match the gender so the loop continues. The best solution would be to analyze strings instead of characters:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String s = in.readLine();
Remember to use equals method instead of == in string comparison.
You pressed return after pressing h; you won't see the 'h' until you do so, but then you'll still see the return (and by the looks of it, that's coming out as two characters, possibly '\r' and '\n') before you see the next character.
You may want to read a line of text at a time, instead of a single character - you'll only see the input when the user presses return anyway, and it means you don't need to worry about this particular aspect.
You could use Scanner for this, or a BufferedReader wrapping System.in.
Use Scanner scan = new Scanner(System.in)
Here is the working version of your code....
public class Info{
public static void main (String[]args) throws IOException{
char gen;
Scanner scan = new Scanner(System.in); // Change made here
while(true) {
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen= scan.next().charAt(0); // Change made here
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
else{ // Change made here
System.out.println();
System.out.println("Your Option is not Available, pls try again");
continue;
}
}
System.out.println("\nGENDER = "+gen);
}
}

Categories

Resources