Take the whole line of a java chain and lenth - java

I am trying to make a java program that given a string, I return the length of it, but I do not know why it does not catch me all. I'm starting with the programing. I've got here.
import java.util.Scanner;
public class lengt {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String cad = in.next();
System.out.println (cad);
System.out.println ("The length is:" + cad.length ());
}
}

There is a problem in your solution. in.next(); just take the first word of the chain, the one that is most immediate. If instead of using that you put it in.nextLine(); It takes you all the line you enter. You also have to be careful with length, which goes from 0 to n-1, when it comes to taking the length, since you could take one more and unnecessary. The solution for the problem that you pose would be, and there may be more, but one valid
import java.util.Scanner;
public class Example {
public static void main (String [] args) {
Scanner in= new Scanner (System.in);
String cad = in.nextLine();
System.out.println (cad);
System.out.println ("The length is:" + cad.length() - 1); //you can remove -1
}
}

Related

Alternative for an infinite loop in java while using scanner.hasNext() with scanner argument System.in

Infinite loop using System.in and scanner.hasNext()
While taking input from user and storing it in a list newcomer(like me) generally thinks of using Scanner class for input and check for next input from user with hasNext() method as below. But often forgets the program will keep asking the user to provide input never endingly. What happens is as each time user press enter the hasNext() method thinks another input is generated and loop continues (Keep in mind pressing enter multiple times wont make a difference).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
List<String> wordsList = new ArrayList<String>();
while (scanner.hasNextLine())
wordsList.add(scanner.nextLine()); // Keeps asking user for inputs (never ending loop)
scanner.close();
for (String word : wordsList)
System.out.println(word);
}
}
Que. What are the working alternatives for above process which let user dynamically decide number of inputs without mentioning the total inputs anywhere.
Since you require that the user can enter any valid String as input, then you can:
Option 1:
The user can enter the number of entries they are going to give, before they give them. So then you only need to loop for the requested number of times. For example:
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of entries: ");
String[] wordsArray = new String[scanner.nextInt()];
scanner.nextLine(); //Skip the end of the line which contains the user's number of entries.
for (int i = 0; i < wordsArray.length; ++i) {
System.out.print("Entry " + (i + 1) + ": ");
wordsArray[i] = scanner.nextLine();
}
for (String word : wordsArray)
System.out.println(word);
}
}
Option 2:
If even the user does not know from the beggining how many entries they want, then you can ask them after every entry, like so:
import java.util.ArrayList;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
ArrayList<String> wordsList = new ArrayList<>();
do {
System.out.print("Entry " + (wordsList.size() + 1) + ": ");
wordsList.add(scanner.nextLine());
System.out.print("Enter an empty/blank line to insert another word, or anything else to stop and exit: ");
}
while (scanner.nextLine().trim().equals(""));
for (String word : wordsList)
System.out.println(word);
}
}
I know that this (the second) option may be a bit boring for the user to enter every time if they want to quit or not, but the only thing they have to do in order to quit the program (from the second option) is to type anything which will produce a non empty/blank line. They can simply hit a single ENTER key to continue giving entries.

Java if (Yes or No Statement)

Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class

my program reads from the file but cant find the words

So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()

Counting the number of strings remaining to be read in standard input using recursion

I want to write a method that has a Scanner parameter associated with a stream of input and counts the number of Strings within the input. However, I have a stack overflow exception. Can you tell me the reason? Thank you a lot.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(count(input));
}
public static int count(Scanner input) {
if (input.hasNextLine())
return 1 + count(input);
else
return 1;
}
}
You need to call nextLine() on input in the line return 1 + count(input). You are checking for the next line, but nothing actually consumes it. This means the Scanner never runs out of lines to process.
Since your question states that you want to count the number of strings in a given input, then the code below will do just that, recursively. The other answer's suggestion counts the number of lines in a given input.
Note: Scanner#next() uses spaces (' ') as the default delimiter.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(count(input));
}
public static int count(Scanner input) {
if (input.hasNext()) {
input.next(); // move Scanner's position to the next string
return 1 + count(input);
}
return 0;
}
}
Input:
The dog barks loudly.
Output:
4

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Categories