//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
Related
This question already has answers here:
How to get out of while loop in java with Scanner method "hasNext" as condition?
(9 answers)
Closed 2 years ago.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
I have no idea why the last line is not getting executed. Someone please point out where I did wrong.
Thank you.
Your code is requesting a new string as input and continuing the loop if it's not empty. This is making your while loop a never-ending loop. That is the reason the last line is not executing. You can insert an if-statement in the loop for an exit string.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(item.equals("/")) {
break;
}
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
Now when you enter the value "/" as the input, it will get out of the while loop and the last line will execute.
I am beginner in Java & I am assigned with a lot of programs for my project this week. However, this one is confusing me for a long time now. I wrote a code for it but it is not displaying any result. There are no syntax errors btw! Have a look- Thank You!
import java.util.*;
import java.lang.*;
public class primeWord_reverser
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,p,flag=0;
System.out.println("Enter the sentence:");
String SEN=sc.next();
SEN=SEN.toUpperCase();
SEN=SEN+" ";
int L=SEN.length();
StringBuilder fnalS= new StringBuilder("");
StringBuilder finalS=new StringBuilder("");
for(i=0;i<L-1;i++)
{
char chr=SEN.charAt(i);
if (chr!=' ')
{
fnalS.insert(fnalS.length(),chr);
}
else if(chr==' ')
{
int LfnalS=fnalS.length();
int m=LfnalS/2;
for(p=2;p<=m;p++)
{
if(LfnalS%p==0)
{
flag++;
}
}
if(flag==0)
{
fnalS.reverse();
finalS.append(" "+fnalS);
}
else if(flag>0)
{
finalS.append(" "+fnalS);
}
fnalS=new StringBuilder("");
flag=0;
}
}
System.out.println("the sentence is: "+finalS);
}
}
Try to change your code of:
String SEN = sc.next();
to
String SEN = sc.nextLine();
and remove -1 on your for loop:
for(i=0;i<L-1;i++)
to
for(i=0;i<L;i++)
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);
}
I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}
If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}