I'am trying to call a method called "cnpPacient".After running this i get a NoSuchElementException in the line where i read variable " cnp ".
static void cnpPacient() {
Scanner x = new Scanner(System.in);
System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
int cnp = x.nextInt();
x.close();
}
How can i fix it ?
Works fine for me when provide 2 as input and it printed the same.
public static void main(String[] args) {
cnpPacient();
}
static void cnpPacient() {
Scanner x = new Scanner(System.in);
System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
int cnp = x.nextInt();
System.out.println(cnp);
x.close();
}
Output:
INTRODUCETI CNP-ul PACIENTULUI :
2
2
Related
public class Solution {
public static void main(String args[])
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
int input1=sc.nextInt();
sc.nextLine();
String str1=sc.nextLine();
Double input2=sc.nextDouble();
}
}
}
This is my code. I only got this exception in "int" and "double" input only in for loop. IF I write it out-side of for loop it working fine. Please any one can help me solve this problem, because I am getting this error in my TCS exam.
Unfortunately your question does no give me much information, however I will try to answer anyway (need that rep). Im assuming the issue you run into is a InputMismatchException ? This is probably something to do with you trying to pass a double (i.e. 12.0) into an int. Using something like System.out.println("Enter Int Input:") can help you highlight which input type you should be providing on the line. try/catch blocks can stop the error being thrown.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
for (int i = 0; i < 5; i++) {
System.out.println("i: " + i);
System.out.println("Enter Int Value:");
int input1 = sc.nextInt();
sc.nextLine();
System.out.println("Enter String Value:");
String str1 = sc.nextLine();
System.out.println("Enter Double Value:");
Double input2 = sc.nextDouble();
}
} catch (InputMismatchException e) {
System.out.println("Invalid input entered for variable type.");
}
}
I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}
Input Format
Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and then the line content received as input:
Sample Output
Hello world
I am a file
Read me until end-of-file.
Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:
Hello world
Here is my code:
public class Solution {
public static void main(String[] args) {
check(1); // call check method
}
static void check(int count) {
Scanner s = new Scanner(System.in);
if(s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
}
Your code does not work because you create a new Scanner object in every recursive call.
You should not use recursion for this anyways, do it iteratively instead.
Iterative version
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int count = 1;
while(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
}
}
}
Recursive version
public class Solution {
private Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in); // initialize only once
check(1);
}
public static void check(int count) {
if(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
check(count + 1);
}
}
}
Change
if (s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
to:
while (s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
while loops continues until the data exists, where as if checks for only once.
Scanner is kind of a BufferedReader (I'm not telling about inheritance or something. I'm telling they both have buffers. Scanner has just a small one). So after you enter text in the Console, those are read() from System.in and stored in the buffer inside the Scanner.
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
s1.hasNext();
Scanner s2 = new Scanner(System.in);
while(true){
System.out.println("Read line:: " + s2.nextLine());
}
}
Use the following input to the Scanner:
line 1
line 2
line 3
line 4
You will get the output:
Read line:: e 1
Read line:: line 2
Read line:: line 3
Read line:: line 4
I think you might know the reason to this output. Some characters of the first line are in the Scanner s1. Therefore don't create 2 Scanners to take input from same Stream.
You can change your code as follows to get required output.
private static Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in);
check(1); // call check method
}
static void check(int count) {
if (s.hasNextLine()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
You can use s.hasNextLine() instead of s.hasNext() as you are reading line by line.
No need to use s.hasNextLine()==true as that statement will be true if and only if s.hasNextLine() is true.
You can give EOF character to the console using Ctrl+Z in Windows system and Ctrl+D in Unix. As I know, you can't send EOF character using the output window of NetBeans.
If using recursion is a requirement, you can use a helper function:
static void check(int count) {
Scanner s = new Scanner(System.in);
check(count, s);
}
static void check(int count, Scanner scanner) {
if(!scanner.hasNext()) {
return;
}
String ns = scanner.nextLine();
System.out.println(count + " " + ns);
check(++count, scanner);
}
Notice how new Scanner(System.in) is only called once.
public static void main(String[] args) {
List<String> eol = new ArrayList<String>();
Scanner in=new Scanner(System.in);
int t=1;
while(in.hasNext()){
eol.add(in.nextLine());
}
for (String i:eol){
System.out.println(t+" "+i);
t++;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()){
System.out.println(count++ + " " + scan.nextLine());
}
}
Here is the error free program.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()) {
String s = scan.nextLine();
System.out.println(count + " " + s);
count++;
}
}
}
Scanner scanner = new Scanner(System.in);
int i = 1;
while(scanner.hasNext()) {
System.out.println(i + " " + scanner.nextLine());
i++;
}
Use while instead of if,but recursive version is better.Here is iterative version:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
{
int i=0;
while(sc.hasNext()==true)
{
i=i+1;
String s=sc.nextLine();
System.out.println(i+" "+s);
};
}
}
}
java.util.Scanner.hasNext() basically helps you to read the input. This method returns true if this Scanner has another token of any type in its input. Returns false otherwise.
Check below code snippet,
while(sc.hasNext()) {
System.out.println(i + " " + sc.nextLine());
i++;
}
You can find complete code at below link,
https://github.com/hetalrachh/HackerRank/blob/master/Practice/Java/Introduction/EndOfFile.java
you can try like this to get desired result:
public class EOF {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i =1;scan.hasNext();i++) {
String line = scan.nextLine();
System.out.println(i + " " + line);
}
scan.close();
}
}
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=1; scan.hasNext() ;
System.out.println(i++ +" "+scan.nextLine()));
}
}
Basically, I want to use to put a value into main and set it up so I can use the word/words entered into main so I can use the code.
public static String L33TLanguageSupport(String s) {
Scanner scan =new Scanner (s);
char o = 0;
char O=0;
char e=0, E=0, a=0, A= 0;
return s
.replace(o, (char) 0)
.replace(O,(char) 0)
.replace(e, (char) 3)
.replace(E,(char) 3)
.replace(a, (char)4)
.replace(A, (char)4);
}
public static void main (String[] arg) {
System.out.println(L33TLanguageSupport("cow life" ));
}
You need to read the user input using Scanner in your desired method, then retrieve the result into a variable and send it to another method.
Adapted from your posted code:
public static String L33TLanguageSupport(String s) {
//remove this from here
//Scanner scan =new Scanner (s);
//do what it must do...
}
public static void main (String[] arg) {
//System.out.println(L33TLanguageSupport("cow life" ));
//creating the scanner to read user input
Scanner scanner = new Scanner(System.in);
//showing a nice message to user
System.out.print("Enter a word: ");
//reading the user input (the whole line until user press Enter key)
String input = scanner.readLine();
//applying the method to user input
String output = L33TLanguageSupport(input);
//showing to user the result of the processing
System.out.println("Result: " + output);
//closing the scanner resources
scanner.close();
}
You could get the same by doing java main cow life and then passing in those arguments to the L33tLanguagesupport object concat'd together.
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for(String arg : args) sb.append(arg).append(" ");
System.out.println(sb.toString().trim());
}
//I am not able to figure out what is wrong? Please help me. I was able to use the //scanner .I am not able to input the values.Java.Util.NoSuchElementException: No Line //Found.
//String arrayValue = null;
int Rows= boardsize, Columns=boardsize;
int[][] sudokuArray = new int[Rows][Columns];
String[] sudokuTempArray;
String delimiter = "\\,";
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
for(int i=0;i<Rows;i++ ){
System.out.println("Enter the value of array separated by ',' for row" + i);
while(userInput.hasNext())
{
String arrayValue = userInput.next();
sudokuTempArray = arrayValue.split(delimiter);
if(sudokuTempArray.length == Rows)
{
for (int j = 0;j<Columns;j++)
{
sudokuArray[i][j] = Integer.parseInt(sudokuTempArray[j]);
System.out.println(sudokuArray[i][j]);
}
}
}
/*
else
{
System.out.println("Try again!");
}*/
}
If you have used a scanner previously reading from System.in and have closed that scanner, you will have closed the System.in InputStream.
Have you previously closed a scanner reading from System.in?
Yes this is a common error. Look at my answer to this question.
java - Scanner class NoSuchElementFoundException
He essentially closed the input in another method, which you are likely doing as well.
Search for .close in your code base.
See this:
java - Scanner class NoSuchElementFoundException
import java.util.*;
import java.util.StringTokenizer;
class shift
{
Scanner sc=new Scanner(System.in);
void test(int x)
{
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s);
String wen="";
{
while(st.hasMoreTokens())
{
String temp=st.nextToken();
for(int i=1;i<=x;i++)
{
wen=wen+temp+" ";
}
}
System.out.print(wen);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
shift reff=new shift();
if(n<=0)
{
System.out.print("EMPTY");
}
else
{
reff.test(n);
}
}
}
//output : java.util.NoSuchElementException: No line found