How does Boolean value work in this program? - java

public class HelloWorld{
public static void main(String [] args){
boolean found = false;
inputInfo = "do";
String temp = "yes/no/do/you";
Scanner scan = new Scanner(temp); // caseS scanner class
scan.useDelimiter("/"); // Delimiter
String[] caseArray = new String[100];
while (scan.hasNext()) {
for (int i = 0; i < caseArray.length; i++) {
caseArray[i] = scan.next();
}
for(int j = 0; j< caseArray.length; j++) {
if(caseArray[j].equals(inputInfo)) {
found = true;
break;
}
}
if(found){
System.out.print("product found");
} else{
System.out.print("product not found");
}
}
}
}
I have a variable called temp which stores a String value, which is separated by a Delimiter("/"). I would like to go through all the elements in the String and print "product found" if the element exists and print "product not found" if the elements doesn't exists.
While running the program I got an error like:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
Could someone tell as to why this error occurs and how to correct it?

caseArray has a hundred elements and you're next() for each even though the string you're splitting only has four elements in it.
Since the temp string is hard coded, you don't really need a scanner there. In fact, it would be much simpler to hold it as an array or a list to begin with:
List<String> cases = Arrays.asList("yes", "no", "do", "you");
found = cases.contains(inputInfo);

Related

Creating an else condition in a loop if string does not exist in an array

The output i need
enter name: john
name not found in array
Here is my pseudocode
//ask for name
System.out.print("enter name")
name = sc.nextLine()
//loop to check if name exists in my array
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{ code to be executed if name is found in arrayofnames }
}
I tried putting an else/else if condition after the if but it executes the code arrayofnames.length times. How do I only make it print something like "name not found in array" only once then break?
You can have a flag, which you can test after the loop
System.out.print("enter name")
name = sc.nextLine()
boolean found = false;
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{
found = true;
break;
}
}
if (!found) System.out.println ("Not found");
public static void main(String[] args) {
String name = "jhn";
String[] arrayofnames = {"john", "tomer", "roy", "natalie"};
IsName(name, arrayofnames);
}
public static void IsName(String _name, String[] _arrayofnames){
boolean a = false;
for (String name : _arrayofnames) {
if(name == _name){
System.out.println("name is in the array");
a = true;
}
}
if(!a){
System.out.println("name is not in the array");
}
}
You can solve this problem by putting your String[] arrayOfNames into an ArrayList<> and simply checking if the ArrayList<> contains the name given by the user.
String[] arrayOfNames = {"Angelo", "David", "John"};
String name = "Angelo"; //the name given by the user
ArrayList<String> newArray = new ArrayList<>(Arrays.asList(arrayOfNames));
//check too see if the ArrayList contains the name
if (newArray.contains(name))
System.out.println("Name found in array");
else
System.out.println("Name not found in array");
If you want your code more compact, you can also use Streams to check if any element of the array equals the given String like this:
boolean found = Arrays.stream(arrayofnames).anyMatch(n -> n.equals(name));
if(found) {
//code to be executed if name is found in arrayofnames
}

Java.util.Scanner: NoSuchElementException, on 2nd input from user [duplicate]

This question already has answers here:
Scanner NoSuchElementException
(2 answers)
Closed 2 years ago.
I am running into an error within my program when trying to get input from user. Basically what the program is, it is to pull data from two different exported txt files which I will then cross reference from each of them. At this point I am just trying to test out the file information gathering that the program is going to do prior to cross referencing.
What is happening, I read the one file which is "FromFile.txt" and then it will print out everything and then ask what the other file name that we need to test. At this point it will then throw that error the 2nd time it asks for the input from the user.
I am having difficulties trying to figure out why this is throwing the error
This is the error that is being thrown.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at CrossReferencingTool.getInputString(CrossReferencingTool.java:98)
at CrossReferencingTool.main(CrossReferencingTool.java:23)
Below is the code where it is having the error.
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next(); <----------------- This is the line where it is throwing the error
input.close();
return string;
}
below is the overall code that is being ran.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CrossReferencingTool {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<ArrayList<String>> list1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> list2 = new ArrayList<ArrayList<String>>();
System.out.println("What is the filename of the file you want to cross reference from:");
File file1 = new File(getInputString());
populateList(file1, list1);
printList(list1);
System.out.println("\nwhat is the filename of the file you want to cross reference with:");
File file2 = new File(getInputString());
populateList(file2, list2);
printList(list2);
}
private static void printList(ArrayList<ArrayList<String>> list) {
String row;
for(int x = 0; x < list.size(); x++) {
row = "";
for(int y = 0; y < list.get(x).size(); y++) {
row += list.get(x).get(y);
if( (y + 1) < (list.get(x).size())) {
row += ", ";
}
}
System.out.println(row);
}
}
private static void populateList(File file, ArrayList<ArrayList<String>> list) throws FileNotFoundException {
Scanner reader = new Scanner(file);
String splitLine[];
String line;
ArrayList<String> internalList;
while(reader.hasNextLine()) {
internalList = new ArrayList<String>();
line = reader.nextLine();
splitLine = line.split(",");
for(int x = 0; x < splitLine.length; x++) {
internalList.add(splitLine[x]);
}
list.add(internalList);
internalList = null;
}
reader.close();
}
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next();
input.close();
return string;
}
}
Figured out this was because I closed out the scanner on each time I would use the getInputString() function. this would create and then also close out a scanner everytime it is called I do not know why this is causing this though.
could you try to use input.nextLine() instead of input.next() inside your getInputString() method?

What should I do to fix this scanner-related bug?

Even though this code compiles:
import java.util.Scanner; // imports the Scanner class from the java.util package
public class ScannerPractice {
public static void main(String args[]) {
Scanner word = new Scanner("word 1 2 3 4"); // creates a new Scanner objecrt with a string as its input
String scaStr = word.nextLine(); // converts scanner to string
String strArr[] = new String[10];
// as long as the scanner has another character...
for (int i = 0; i < scaStr.length(); i++) {
int j = 0;
String k = "";
// if the next token is an integer...
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
// otherwise, skip over that token
else {
word.next();
}
}
String k = "";
// for each character in charArr
for (int i = 0; i < strArr.length; i++) {
// Accumulate each element of charArr to k
k += " " + strArr[i];
}
System.out.print(k);
}
}
I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ScannerPractice.main(ScannerPractice.java:28)
The exception refers to line 28, which is:
word.next();
I have tried looking at my for loop that assigns values to the string array, but I still couldn't find the error.
I am racking my brain trying to solve this. Even a hint would be most appreciated.
You already consumed all the strings in your Scanner on this line.
String scaStr = word.nextLine();
So, the scanner doesn't have more characteres and that's why you are getting that error.
I think you don't need to 'convert your scanner to string' in order to iterate over it. You can simply use a while to check if your Scanner has remaining characteres.
while(word.hasNext()) {
int j = 0;
String k = "";
// if the next token is an integer...
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
// otherwise, skip over that token
else {
word.next();
}
}
Change the loop to check whether the scanner has any more input:
Scanner word = new Scanner("word 1 2 3 4");
String strArr[] = new String[10];
int i = 0;
while (word.hasNext()) {
int j = 0;
String k = "";
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
else {
word.next();
}
}
It doesn't make sense to iterate over the string you already consumed from the scanner, because then you lose the ability to match tokens. If you wanted to use a string tokenizer you could do that, but then you can drop using the scanner.
If you want your code to run correctly change the input to:
Scanner word = new Scanner("word"+"\n"+"1"+"\n"+"2"+"\n"+"3"+"\n"+"4");
adding newline character solves the problem.

Java programming, String to String conversion error during compilation. Taking input from user and storing it

I am making a program to a get a case input from the user and then store that case entry. However, I am getting an error during compilation,
demo576.java:44: error: incompatible types: String cannot be converted
to String [] h=z.Batman();
^ 1 error
the code is as follows:-
import java.util.Scanner;
class demo576
{
public static void main (String args[])
{
Scanner s=new Scanner (System.in);
fun z=new fun();
String x=z.Batman();
System.out.println(x);
int p=s.nextInt();
String h[]=new String[3];
int i;
for (i=0;i<3;i++)
{
h=z.Batman();
}
for(i=0;i<3;i++)
{
System.out.println(h);
}
}
}
I guess this should suffice:
for(int i=0; i<3; i++) {
h[i] = z.Batman();
}
Your print loop needs fixing:
for(int i=0;i<3;i++) {
System.out.println(h[i]);
}
P.S. Here is my motto for helping StackOverflow users:
System.out.println("He is not a hero. He is a silent guardian, a watchful protector; A DARK KNIGHT!");
You are trying to set an array equal to a string. Try this instead (first for loop)
for (i = 0; i < 3; i++)
h[i] = z.Batman();
Good luck!

java String index out of bounds error

I'm trying to reverse a sentence. (if the sentence is "i am a cat", then the result should be "cat a am I") The problem is that I'm getting an index out of bounds error, I'm not sure how to fix the problem. Not sure if my index is wrong or if the substring part is wrong. I'm just a beginner in Java, so any help is really appreciated. error: String index out of range: -1
Thanks
public class ReverseWords {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = in.nextLine();
File f = new File(fileName);
try {
Scanner input = new Scanner(f);
int x = 1;
int n = input.nextInt();
while (x<n) {
String line = input.nextLine();
Queue<String> q = new LinkedList<String>();
q.add(line);
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
ArrayList<String> a = new ArrayList<String>();
while (line.length() > 0) {
a.add(word);
q.remove(word);
}
System.out.println("Case #" + x);
for (int i = a.size(); i != 0; i--) {
System.out.print(a.get(i));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
From the Java documentation of String:
public int indexOf(int ch)
...
If no such character occurs in this string, then -1 is returned.
are you prepared for that there is no more whitespace?
For example at the last iteration...
But it looks like there are other bugs, too.
Your problem would be with a line like the following:
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
whenever indexOf doesn't find what it's looking for, it will return -1. If you ever try to use that index on the string, you'll be indexing at -1 which is out of bounds.
it looks like you're trying to find the space in a line that has no space.

Categories

Resources