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.
Related
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;
}
}
So I need to write a program that reads a sentence of five words, and finds the longest word in the sentence and displays it. If there happen to be two equally large words, it just displays the first largest word.
import java.util.Scanner;
public class Longest_Word {
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.print("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
q = scanner.next();
w = scanner.next();
e = scanner.next();
r = scanner.next();
t = scanner.next();
System.out.println(q + " " + r);
}
}
You can probably tell where I'm stuck. I really don't know how to compare these words. The first thing that came to mind was to use if/else to compare them individually, using line.length().
Can't use array, .split, or loops (sadly).
Show your teacher this!
Stream.generate(scanner::next).limit(5)
.max(Comparator.comparing(String::length))
.ifPresent(System.out::println);
if/else and loops are the same for this problem.
String largerString = q;
if(w.length()>largerString.length())
{
largerString = w;
}
if(e.length()>largerString.length())
{
largerString = e;
}
if(r.length()>largerString.length())
{
largerString = r;
}
if(t.length()>largerString.length())
{
largerString = t;
}
System.out.println(largerString);
Given the constraints I suggest you use if statements as you assumed.
import java.util.Scanner;
public class Longest_Word {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.print("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
q = scanner.next();
String longest = q;
w = scanner.next();
if (w.length()>longest.length())
longest = w;
e = scanner.next();
if (e.length()>longest.length())
longest = e;
r = scanner.next();
if (r.length()>longest.length())
longest = r;
t = scanner.next();
if (t.length()>longest.length())
longest = t;
System.out.println(longest);
}
}
Read all the values in list and use Java Streams to find longest String
String logestStr = list.stream().max(Comparator.comparing(String::length)).get();
If you just want to show the largest word, you can do it as follows, and it will be dynamic too in case the number of words is more than 5.
Scanner in = new Scanner(System.in);
String line;
String q, w, e, r, t;
System.out.println("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);
String maxWord = "";
while(scanner.hasNext()){
String word =scanner.next();
if(word.length()>maxWord.length())
maxWord = word;
}
System.out.println(maxWord);
I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}
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;
}
I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}