Java returning entered text - java

My first post here on stackoverflow.
The task is:
Write a method that shall return a String, the method has no parameters. The method is going to read some word from the keyboard. The inputs ends with the word "END" the method should return this whole text as a long row:
"HI" "HELLO" "HOW" "END"
Make is so that the method return the string
HIHELLOHOW
MY CODE IS:
import java.util.*;
public class Upg13_IS_IT_tenta {
String x, y, c, v;
public String text(){
System.out.println("Enter your first letter");
Scanner sc = new Scanner(System.in); //Can you even make this outside main?
x = sc.next();
y = sc.next();
c = sc.next();
v = sc.next(); // Here I assign every word with a variable which i later will return. (at the bottom //i write return x + y + c;). This is so that i get the string "HIHELLOWHOW"
sc.next();
sc.next();
sc.next();
sc.next(); // Here I want to return all the input text as a long row
return x + y + c;
}
}
I know that my code has a lot of errors in it, I am new to Java so I would like so help and explaining of what I've done wrong. THANKS!

you can do something like this:
public String text(){
InputStreamReader iReader = new InputStreamReader(System.in);
BufferedReader bReader = new BufferedReader(iReader);
String line = "";
String outputString = "";
while ((line = bReader.readLine()) != null) {
outputString += line;
}
return outputString;
}

Probably you want something like
public String text() {
String input;
String output = "";
Scanner sc = new Scanner(System.in);
input = sc.next();
while (! input.equals("END")) {
output = output + input;
input = sc.next();
}
return output;
}

What you have done now is build a program that can only handle one specific input.
You might want to aim for something more reusable:
public String text(){
System.out.println("Talk to me:");
Scanner sc = new Scanner(System.in);
StringBuilder text = new StringBuilder();
while(!text.toString().endsWith("END"))
{
text.append(sc.next());
}
return text.toString().substring(0, text.toString().length()-3);
}
This builds a single String out of your input, stops when the String ends with "END" and returns the String without the last 3 letters ("END").

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

Change Search function from String to Integers

This is my function that used to search String (Student Name) inside the text file. But is there any other way to change this function to search integers (Student ID) inside the text file?
String STUD_NAME;
System.out.println("ENTER STUDENT NAME: ");
Scanner name = new Scanner(System.in);
STUD_NAME = name.nextLine();
Pattern pattern = Pattern.compile("[A-Za-z]*");
if (name.hasNext(pattern)) {
FileReader fr = new FileReader("student.txt");
BufferedReader br = new BufferedReader(fr);
String s;
String keyword = STUD_NAME;
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
System.out.println(s);
}
}
} else {
System.out.println("PLEASE ENTER ALPHABETS NOT NUMBERS/SYMBOLS");
}
in your code replace "[A-Za-z]*" with "[\d]+"
This will replace your search for a string to search for integers number.
if you know exactly how many numbers is an ID you can use the following:
"[\d]{5}"
and will match an integer of 5 numbers like: 24453

Reading multiple lines into a scanner object in Java

I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}

ChatBot return bug

I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.

How to type in a string that will be assigned to a variable?

I need my program to ask the user to type in a String which will be assigned to a variable eg:string in the case below so the array list can be searched for a String containing the String entered by the user.
public void search(){
String string = "";
for (int i = 0; i < wordArray.size(); i++){
if (wordArray.get(i).contains(string) == true){
System.out.println(wordArray.get(i));
}
else{
System.out.println("No words match your search.");
}
}
}
If this is no gui application you can use System.in.
Scanner s = new Scanner(System.in);
String string = s.readLine();
Use the Scanner api:
Scanner s = new Scanner(System.in);
String string = s.nextLine();
....
s.close();
... or Console from System.console() :
String string = System.console().readLine();
(You need to check that you get a console back from System.console() if you want to be sure!)
here's how you read from keyboard using JavaIo
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("please type in a value ");
String str = br.readLine();

Categories