Why is this code getting a Java NoSuchElement exception? - java

I have traced through this code and can't figure out how to fix it. When running the code why wouldn't the user be prompted for input rather than Java determining that there is no input? Error trace below.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
input.close();
return next_string;
}
Here is the error --
How many items are you entering?: 2
Enter the next string:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at SortAsInserted.GetNextString(SortAsInserted.java:40)
at SortAsInserted.main(SortAsInserted.java:10)

The simple answer is when you close Scanner -- underlying input stream also closes:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
To fix this create Scanner once in main:
public class SortAsInserted {
static Scanner input;
public static void main(String[] _) {
input = new Scanner(System.in);
....
input.close();
}

Remove input.close(); from the code

Removing the scanner.close() method from two functions will solve your problem.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
//input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
// input.close();
return next_string;
}
}

Related

To find the single digit sum of palindrome numbers in array

I tried to check the palindrome number and find the single digit sum of the palindrome numbers, but my code is not returning the proper value (I am finding it difficult to return the value of sum from the loops). Can anyone help me getting the mistake. Any help will be appriciated.
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
System.out.println(SumOfPalindromeNumber(inp));
}
private static int SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
sumpal+=inp[i];
if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
}
}
return sumpal;
}
private static int singledigitsum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singledigitsum(sum1);
}
return sum1;
}
}
Enter numbers
Check which numbers are palindromes.
If that number is a palindrome then find sum of its digits.
Code:
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
SumOfPalindrome sumOfPalindrome=new SumOfPalindrome();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(sumOfPalindrome.isPallindrone(inp[i]))
{
System.out.println("No -> "+inp[i]+" Sum->"+sumOfPalindrome.sumOfDigits(inp[i]));
}
}
}//
public boolean isPallindrone(int no)
{
int r,sum=0,temp;
temp=no;
while(no>0){
r=no%10; //getting remainder
sum=(sum*10)+r;
no=no/10;
}
if(temp==sum)
{
return true;
}
else
{
return false;
}
}
public int sumOfDigits(int no)
{
int sum = 0;
while (no != 0)
{
sum = sum + no % 10;
no = no/10;
}
return sum;
}
}
I did not understand the purpose of sumpal in your code. You wanted a method which return sumOfPalindromes in an array. I commented the part which was wrong.
import java.util.Scanner;
public class SumOfPalindrome_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
//System.out.println(SumOfPalindromeNumber(inp));
SumOfPalindromeNumber(inp);
}
private static void SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
// sumpal+=inp[i];
/*if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
*/
System.out.println(singleDigitSum(inp[i]));
}
}
}
private static int singleDigitSum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singleDigitSum(sum1);
}
return sum1;
}
}
Apologies if this is not the case but this seems like you are looking for answers to a coding test.

My bot program accepts user input and then instead of replying, does nothing

I created a bot and used a snippet of code I invented called "simplify" to dramatically shorten java commands.
Only problem is, the bot program I made with it doesn't work. It's supposed to search the user input for keywords and reply accordingly, but all it really does is accept user input and then turn off. What did I do wrong?
import java.util.*;
public class bot{
//"simplify" and "bot" created by #genisome, All rights reserved.
System.out.println(in);
}
public static void print(String in){
System.out.println(in);
}
public static void print(double in){
System.out.println(in);
}
public static void print(long in){
System.out.println(in);
}
public static void print(boolean in){
System.out.println(in);
}
public static void print(float in){
System.out.println(in);
}
//scan below
public static void scan(int dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextInt();
}
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
public static void scan(double dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextDouble();
}
public static void scan(float dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextFloat();
}
public static void scan(boolean dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextBoolean();
}
public static void random(int min, int max, int dumpinto){
Random x = new Random();
dumpinto = x.nextInt(max) + min;
}
public static void main (String[] x){
int score;
String[] badcomputerresponse = {"that sucks, sorry", "sorry about that", "bummer", "shit", "aw, damn"};
String[] goodcomputerresponse = {"awesome.", "me too", "great", "cool", "I'm not bad myself"};
String[] goodwords = {"good", "fine", "dandy", "awesome", "cool", "swell", "great", "amazing", "ok", "okay", "well", "happy", "thrilled"};
String[] badwords = {"shitty", "terrible", "sad", "bad", "crappy", "terrible", "sucky", "up shit creek", "pathetic", "miserable", "badly", "terribly", "miserably"};
String input = "";
print("Hey there, how are you doing?");
scan(input);
for (int counter = 0; counter < goodwords.length; counter++){
if (input.contains(goodwords[counter])){
if (input.contains("not")){
sadanswer(badcomputerresponse);
}
else{
happyanswer(goodcomputerresponse);
}
}
}
for (int count2 = 0; count2 < badwords.length; count2++){
if (input.contains(badwords[count2])){
if (input.contains("not")){
happyanswer(goodcomputerresponse);
}
else{
sadanswer(badcomputerresponse);
}
}
}
}
public static void sadanswer(String[] badcomputerresponse){
int randomanswer = 0;
random(0, badcomputerresponse.length, randomanswer);
print(badcomputerresponse[randomanswer]);
}
public static void happyanswer(String[] goodcomputerresponse){
int randomanswer = 0;
random(0, goodcomputerresponse.length, randomanswer);
print(goodcomputerresponse[randomanswer]);
}
}
edit: thank you people who gave me help instead of downvoting me.
To the people who downvoted me, you stink!
First you define a bunch of scan methods like this:
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
Then you call it like this:
String input = "";
print("Hey there, how are you doing?");
scan(input);
That function does not do what it looks like it does. String dumpinto is an input parameter to the method. You can't write output to it. Once the method is done executing, the value that you typed in is lost. After you call scan(input);, the input variable still contains "". (Print it out or use a debugger to verify.)
Your scan method needs to return a value. Better yet, get rid of those methods altogether and just use one Scanner object to get input from the user.

how to declare int as array[] and past the value from main class?

How can I fix this problem? I want to change parameter and pvalue as array
import java.util.*;
public class Test5 {
/**
* #param args the command line arguments
*/
int parameter[];
int pvalue[];
public Test5(int para[], int pv[]){
parameter=para;
pvalue=pv;
}
public void loopi(){
int i = 0,j,k,l;
Scanner sc=new Scanner(System.in);
System.out.print("enter parameter : ");
parameter[i]= sc.nextInt();
char group = 'a';
for(i=1;i<=parameter[i];i++)
{
System.out.print("enter parameter value : ");
pvalue[i]=sc.nextInt();
for(j=1;j<=pvalue[i];j++)
{
System.out.print(" "+j+group+" \n");
}
seat++;
}
}
public static void main(String[] args) {
// TODO code application logic here
int i[] = null;
int j[] = null;
Test5 t=new Test5(i,j);
t.loopi();
}
}
If you want to get the arrays as command line arguments, then you need to convert all of the strings in args to int, you could try something like
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++) {
a[i] = Integer.parseInt(args[i]);
}

For every services I'm getting same price (output)

import java.util.Scanner;
import java.util.Arrays;
public class CarCareChoice{
public static void main(String[] args) {
String[] choices=new String[5];
int j ;
boolean validItem=false;
double price=0.0;
int p;
String str;
//When i'm entering services I'm getting 5.o for all services plz help
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("enter");
str= input.nextLine();
for(j = 0; j < choices.length;j++){
if(Arrays.asList(services).contains(str)){
validItem=true;
price=prices[j];
}
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
}
}
output
enter
Am
service5.0
output
enter
Bm
service5.0
when I enter Am i supposed to get 1.0 for "Bm 2.0 and etc but I'm getting only 5.0
You rather improve your code as following:
System.out.println("enter");
List<String> choiceList = Arrays.asList(services);
str= input.nextLine();
int index = choiceList.indexOf(str);
if ( index!=-1 )
{
price = prices[i];
validItem = true;
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
You need not do this in for loop. Because when you have converted your array to a list then just find the index. If that is -1 then its definitely not a valid item else return the price at that index of the array. ArrayList is backed by an array internally.
import java.util.Arrays;
class Main {
public static final int INVALID_INDEX = -1;
public static void main(String[] args) {
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
String input = "Em";
int index = Arrays.asList(services).indexOf(input);
System.out.println((index!=INVALID_INDEX)? prices[index]+"":"invalid input");
}
}
Use a Map<String,Double> instead if possible.

Display Selected Message String

I'm working on a method that goes through all of my array messages and displays the selected message. I'm new to Java so I'm still trying to figure out methods and Arrays. When I run this, it says that it's successful but it doesn't display anything. Can someone help me figure this out.
package chatbox;
import java.util.Scanner;
public class ChatBox
{
public static void main(String[] args)
{
String chatMessages[] = new String[10];
//declare arrays
chatMessages[0]= "Pepperoni";
chatMessages[1]= "Olives";
chatMessages[2]= "Cheese";
chatMessages[3]= "Onions";
chatMessages[4]= "Bacon";
chatMessages[5]= "Tomato sauce";
chatMessages[6]= "Bell peppers";
chatMessages[7]= "Mushrooms";
chatMessages[8]= "Sausage";
chatMessages[9]= "Beef";
}
Scanner scan = new Scanner (System.in);
public Scanner chatCannedMessage(String chatMessages)
{
for (int i=0;i<chatMessages.length;i++){
System.out.println(chatMessages[i]); //Prints Message
}
System.out.println("Select a message");
String chatMessage = scan.next();
scan.nextLine();
return scan;
}
}
As PM 77-1 said, you never invoked your shoutOutCannedMessage method and also never print out or return any string.
I tried to minimize changes to your code, and I think this might be what you intended to do.
import java.util.Scanner;
public class ShoutBox {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String messages[] = new String[10];
//declare 10 arrays
messages[0] = "Pepperoni";
messages[1] = "Olives";
messages[2] = "Cheese";
messages[3] = "Onions";
messages[4] = "Bacon";
messages[5] = "Tomato sauce";
messages[6] = "Bell peppers";
messages[7] = "Mushrooms";
messages[8] = "Sausage";
messages[9] = "Beef";
String m = new ShoutBox().shoutOutCannedMessage(messages);
System.out.println(m);
}
public String shoutOutCannedMessage(String[] messages) {
for (int i = 0; i < messages.length; i++) {
System.out.println(i+". "+messages[i]); //Should print the messages
}
System.out.println("Select a message");
int idx = scan.nextInt();
String message = messages[idx];
return message;
}
}

Categories

Resources