Using scanner to read from console in Java - java

I have tried using Scanner to read from console into a string object and keep adding the data until the user pushes enter twice .How can I improve my code?
String text;
public void Settext() {
System.out.println("please enter the values for the text :");
String S;
Scanner scn = new Scanner(System.in);
if ((S = scn.next())!= null) {
text += S.split("\\|");
}
scn.close();
}
public String toString() {
Settext();
String S = "the output of document class toString method is " + text;
return S;
}

Use this instead of your if statement -
int noOfNulls = 0;
while(noOfNulls != 2)
{
if ((S = scn.next()) != null)
{
text += S.split("\\|");
noOfNulls = 0;
}
else
noOfNulls++;
}

I think this might help you. Does what you describe. Taking in consideration that a user might press Enter Key several times but no consecutively.
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
String buffer="";
boolean previusEnter=false;
while(readString!=null) {
if (readString.equals("")){
if(previusEnter)
break;
previusEnter=true;
}
else
previusEnter=false;
buffer+= readString+"\n";
if (scanner.hasNextLine())
readString = scanner.nextLine();
else
readString = null;
}

Related

Java scanner test for empty line

I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.

How to take space separated input in Java using BufferedReader?

How to take space separated input in Java using BufferedReader?
Please change the code accordingly, i wanted the values of a, b, n as space seperated integers and then I want to hit Enter after every test cases.
Which means first i'll input the number of test cases then i'll press the Enter key. Then i input the vale of a then i'll press Space, b then again Space then i'll input the value of n, then i'll press the Enter key for the input for the next testcase.
I know that this can be done easily through Scanner but i don't wanna use it because it throws TLE(Time Limit Extended) error on online judges.
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
int testCases = Integer.parseInt(inputString);
double a,b,n,j,t=1;
int i;
int ans [] = new int[testCases];
for(i=0;i<testCases;i++)
{
inputString = br.readLine();
a = Double.parseDouble(inputString);
inputString = br.readLine();
b = Double.parseDouble(inputString);
inputString = br.readLine();
n = Double.parseDouble(inputString);
for(j=0;j<n;j++)
{
if(t==1)
{
a*=2;
t=0;
}
else if(t==0)
{
b*=2;
t=1;
}
}
if(a>b)
ans[i]=(int)(a/b);
else
ans[i]=(int)(b/a);
t=1;
}
for(i=0;i<testCases;i++)
System.out.println(ans[i]);
}catch(Exception e)
{
return;
}
}
First read the number of input lines to be read.
Then parse each line and get the String.
Though I have not added the NumberFormatException handling, but it's a good idea to have that.
Change your for loop like this:
for(i=0;i<testCases;i++){
inputString = br.readLine();
String input[] = inputString.split("\\s+");
a = Double.parseDouble(input[0]);
inputString = br.readLine();
b = Double.parseDouble(input[1]);
inputString = br.readLine();
n = Double.parseDouble(input[2]);
for(j=0;j<n;j++){
if(t==1){
a*=2;
t=0;
}else if(t==0){
b*=2;
t=1;
}
}
if(a>b){
ans[i]=(int)(a/b);
}else{
ans[i]=(int)(b/a);
t=1;
}
}

Not printing out correctly

I am trying to write a program that breaks string by '+' sign. For example, if my input is "1+2+3*4". the program will print 1, 2, 3*4. I used \s*\+\s* as my pattern. However, it doesn't print out when it matches the pattern?
private Scanner kbd = new Scanner(System.in);
private String tokenPattern = "\\s*\\+\\s*"; //pattern
public void repl() {
while(true) {
try {
System.out.print("-> ");
String input = kbd.nextLine();
if (input.equals("quit")) break;
Scanner tokens = new Scanner(input);
while(tokens.hasNext(tokenPattern)) { //figure out why its not printing
String token = tokens.next(tokenPattern);
System.out.println(token);
}
tokens.close();
} catch(Exception e) {
System.out.println("Error, " + e.getMessage());
}
}
System.out.println("bye");
}
You should use findWithHorizon

How do I pull information form a .txt file in Java?

I currently have some code that can take console input, but I need to make it recognize a list of names and test scores.
Code that I currently have:
import java.io.*;
import utils.io.*;
class student
{
String name;
double sResult[];
int result;
double sum;
void getdata()
{
System.out.println("Enter name:");
Name = (string) system.in.read();
int index=0;
for (int counter=1; counter<=5; counter++)
{
System.out.println("Enter result for subject"+counter+":");
sResult[count] = (double) system.in.read();
}
}
public static void CalculateAverage()
{
sum = 0;
for (int i=1;i<=5;i++)
{
sum += sResult[i];
}
return (int) Math.round(sum/(values.length-1));
}
Public static char calculateGrade()
{
result=sum;
if (result>=0 && result <=59)
{
return ('F');
}
else
if (result >=60 && result<=69)
{
return ('E');
}
else
if (result>=0 && result<79)
{
return ('D');
}
else
if (result >=70 && result<=79)
{
return ('C');
}
else
if (result>=80 && result<=89)
{
return ('B');
}
else
if (result>=90 && result<=100)
{
return ('A');
}
}
}
and class test
public class test
{
public static void main(String[] args)
{
Student std;
do
{
std=new Student();
std.getdata();
System.out.println("Student Name:"+std.Name);
System.out.println("Average for"+std.Name+" "+"is:"+std.average());
System.out.println("Grade for"+std.Name+" "+"is:"+std.gradecal());
System.out.println("Want to continue (1-Yes,2-No");
}
while(System.in.read()==1);
}
The text document format is name score1 score2 score3 score4 score5
I only need help figuring out how to import the values, and then I can probably figure out how to rewrite the .txt using PrintWriter.
Thanks in advance for any help!
Here's how you do it with Scanner.
Scanner inputFile = new Scanner(new File("inputfile.txt"));
while(inputFile.hasNext()){ //if there is still something to read
String name = inputFile.next();
int score1 = inputFile.nextInt();
....
int score5 = inputFile.nextInt();
//Do something here with the scores
inputFile.next(); //Read the new line character and prepare for the next iteration
}
For writing back to file, you can check Davy's answer and use a Buffered Writer. Note that the write() method works just like System.out.println() but you need to print \n on your own to go to the new line.
Firstly, you should not have variable names starting with a capital, namely:
string Name;
Only class names should start with a capital.
Also, I'm not even sure if your code compiles. Everywhere you have system.out.println should be System.out.println. Notice that System is a class, so the first letter is a capital
To read data, you can use BufferedReader and to write, you can use BufferedWriter.
Usage:
BufferedReader in = new BufferedReader(new FileReader("FileName.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("OutputFileName.txt"));
in.readLine(); //This reads a single line from the text file
out.write("Your Output Text");
in.close(); // Closes the file input stream
out.close(); // Closes the file output stream
Since you are reading in the format:
name score1 score2 score3 score4 score5
you can use the some String functions to get each field.
String inputLine = in.readLine();
String [] fields = inputLine.split(" "); // Splits at the space
System.out.println(fields[0]); //prints out name
System.out.println(fields[1]); //print out score1
...
public static void main(String... args) throws IOException {
Scanner s = new Scanner(new BufferedReader(new FileReader("textfile.txt")));
while(s.hasNext()){
Student student = new Student(s.next(), s.nextDouble(), s.nextDouble(),
s.nextDouble(), s.nextDouble(), s.nextDouble() ));
// Do something with student
s.next() // consume endline
}
}

Method is undefined for class TestChatBot?

import java.util.*;
public class TestChatBot
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String x = input.nextLine();
TestChatBot e = new TestChatBot();
{
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput = input.nextLine();
while(!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse());
userInput = input.nextLine();
}
}
}
public class ChatBot
{
public String getResponse(String input)
{
Scanner userInput = new Scanner(input);
input = userInput.nextLine();
longestWord(input);
String keyword = "you";
int you = input.indexOf(keyword);
if (you >= 0)
return "I'm not important. Let's talk about you.";
if (input.length() <= 3)
return "Maybe we should move on. Is there anything else you would like to
talk about?";
if (input.length() == 4)
return "Tell me more about " + input;
if(input.length() == 5)
return "Why do you think " + input + "is important?";
else
return "Now we're getting somewhere. How does " + input + "affect you the
most?";
}
private String longestWord(String x)
{
Scanner input = new Scanner(x);
String longest = "";
String temp = input.next();
while (input.hasNext())
{
if (temp.length() > longest.length())
longest = temp;
}
return longest;
}
}
}
In my ChatBotTest class it says that my getResponse() method is undefined for the class TestChatBot... I don't really understand why it says this and it's preventing my code from running. I'm pretty new to Java so I'm sorry for poor/sloppy coding. Any help is greatly appreciated, thank you!
TestChatBot e = new TestChatBot();
Should be
ChatBot e = new ChatBot();
TestChatBox has no getResponse()
Also, your getResponse takes a String argmument. I think you want to pass userInput to it
System.out.println(e.getResponse(userInput));

Categories

Resources