java.util.NoSuchElementException error on multiple while statements - java

Screenshot of error message
Getting this error when I run my code, note that it finds a problem at line 37, but I cannot figure out what it is. Running the first iteration of the scanner method (for input 1) worked fine, and yielded the proper output, but none of the consecutive ones have, and I've been stuck on that issue. Code is below:
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int largest= 0;
int largestEven = 0;
int countOfAllPositive = 0;
int sumOfAll = 0;
try {
Scanner input1 = new Scanner(new File("input1.txt"));
while (input1.hasNextInt()) {
if (input1.nextInt() == 0)
{ break;
} else if (input1.nextInt() < largest)
{ largest = input1.nextInt();
} else if (input1.nextInt() > 0)
{ largestEven += input1.nextInt();
} else if (input1.nextInt() % 2 == 0)
{ countOfAllPositive += input1.nextInt();
} else if (input1.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input2 = new Scanner(new File("input2.txt"));
while (input2.hasNextInt()) {
if (input2.nextInt() == 0)
{ break;
} else if (input2.nextInt() < largest)
{ largest = input2.nextInt();
} else if (input2.nextInt() > 0)
{ largestEven += input2.nextInt();
} else if (input2.nextInt() % 2 == 0)
{ countOfAllPositive += input2.nextInt();
} else if (input2.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input3 = new Scanner(new File("input3.txt"));
while (input3.hasNextInt()) {
if (input3.nextInt() == 0)
{ break;
} else if (input3.nextInt() < largest)
{ largest = input3.nextInt();
} else if (input3.nextInt() > 0)
{ largestEven += input3.nextInt();
} else if (input3.nextInt() % 2 == 0)
{ countOfAllPositive += input3.nextInt();
} else if (input3.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input4 = new Scanner(new File("input4.txt"));
while (input4.hasNextInt()) {
if (input4.nextInt() == 0)
{ break;
} else if (input4.nextInt() < largest)
{ largest = input4.nextInt();
} else if (input4.nextInt() > 0)
{ largestEven += input4.nextInt();
} else if (input4.nextInt() % 2 == 0)
{ countOfAllPositive += input4.nextInt();
} else if (input4.nextInt() < 0)
{ sumOfAll++;
}
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace(); }
System.out.println("The largest integer in the sequence is " + largest);
System.out.println("The largest even integer in the sequence is " + largestEven);
System.out.println("The count of all positive integers in the sequence is " + countOfAllPositive);
System.out.println("The sum of all integers is " + sumOfAll);
}
}

The exception NoSuchElementException in your case is caused by trying to use nextInt() on a file/input that has no more int's left to read, see the Javadoc:
Thrown by various accessor methods to indicate that the element being
requested does not exist.
The reason you get the issue is because every time you call nextInt() in actually uses up an int and moves onto the next one.
So instead of this where you call nextInt() over and over in the if/else if:
if (input1.nextInt() == 0) //Gets the next int
{ break;
} else if (input1.nextInt() < largest) //Gets the next int (different from the previous)
{ largest = input1.nextInt(); //Gets the next int (different from the previous)
... //And so on
You need to do call nextInt() once and assign it to a value then use that value:
//Store the int as a value
int value = input1.nextInt();
//Use the value instead of calling "nextInt()" again
if (value == 0)
{ break;
} else if (value < largest)
{ largest = value;
...

Related

Making an Armstrong number checker but if condition is not working

I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}

How to repeat process in the loops

I'm writing code to let users guess the number. Thay have only two chance to got all
If user put wrong input (Beyond 1-4),
they can do it again. In this case, the user must answer 2 and 4 to get all.
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
//how to repeat in same loop
}
}
Use the break statement
else if (num == 2) {
System.out.println("wow!! you got it");
break;
}
for (int i = 0; i < guessnum.length; i++) {
int count = 1;
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
} else {
if (i != 2) {
System.out.println("number must be 1-4 only, try again,and change another number");
} else {
break;
}
//do again in same loop
}
i++;
}
you can try this
Here is all my code, in two chance the user needs to put 2 and 4 to win.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];
int x=0;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
x++;
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
x++;
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
if (x == 0)
System.out.println("\nyou don't get anything");
if (x == 1)
System.out.println("\nyou got 1 only");
if (x == 2)
System.out.println("\ncongrat!!!! you got all");
}
}
If you wanna use for loop you can write something like this --i; in the last else block after System.out.println("number must be 1-3 only, try again");
So, this code will solve your problem:
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
UPDATE
In my answer above I just said, how to repeat for loop with minimal changes to the original code. As was asked in the title. But #JayPrakash said that it wasn't perfect answer and vote it down. Ok, lets try to find the perfect one:
public static void main(String[] args) {
guess(2, 1, 4, new int[]{2, 4});
}
/**
*
* #param tries tries count
* #param from from range, inclusive
* #param to to range inclusive
* #param puzzled array with puzzled values
* #return array, which contains only puzzled answers from a user
*/
public static int[] guess(int tries, int from, int to, int[] puzzled) {
if (puzzled == null || puzzled.length < 1) throw new IllegalArgumentException("puzzled");
if (Math.abs(from - to) < 1) throw new IllegalArgumentException("range");
if (tries < 1 || Math.abs(from - to) < tries - 1) throw new IllegalArgumentException("tries"); //`tries - 1` because `to` is inclusive
if (from > to) {
int tmp = from; from = to; to = tmp;
}
Scanner sc = new Scanner(System.in);
int answers[] = new int[tries], //all previous user answers
result[] = new int[tries];
System.out.printf("You have only %d chances to get all\n", tries);
int i = 0, j = 0;
while (i < tries && j < puzzled.length) { // `j < puzzled.length` break if all puzzled answers is found
System.out.printf("%d Enter number %d-%d: ", (i + 1), from, to);
int number = sc.nextInt();
if (number < from || number > to) {
System.out.printf("Number must be in %d-%d range only, try again\n", from, to);
continue;
}
if (contains(answers, number, i)) {
System.out.printf("Number %d is used before\n", number);
continue;
}
answers[i++] = number;
if (contains(puzzled, number)) {
System.out.println("Wow!! you got it");
result[j++] = number;
} else {
System.out.println("Not here");
}
}
if (j == puzzled.length)
System.out.println("You got all");
else
System.out.printf("You got %d only\n", j);
return Arrays.copyOfRange(result, 0, j);
}
private static boolean contains(int[] array, int value) {
return contains(array, value, array.length);
}
private static boolean contains(int[] array, int value, int lookTo) {
for (int i = 0; i < lookTo; i++)
if (array[i] == value)
return true;
return false;
}
int i = 1;
Scanner sc = new Scanner(System.in);
do {
System.out.println("you have only two chance to get all");
System.out.print((i) + " Enter number 1-4 : ");
int num = sc.nextInt();
switch (num) {
case 1:
System.out.println("not here");
break;
case 2:
System.out.println("wow!! you got it");
goItOrNot = false;
break;
case 3:
System.out.println("not here");
break;
case 4:
System.out.println("wow!! you got it");
break;
default:
System.out.println("number must be 1-4 only, try again");
break;
}
i++;
}
} while (i < 3);

How do I properly pass a scanner and an int into a function and return the integer value in java?

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.

How do I close my scanner?

I have this code that works but I cannot close my scanner after I'm done. scanner.close() does not work anywhere and using try(Scanner scaner etc. does not seem to work either. Can anyone tell me how to close a scanner in a code like mine?
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
int input;
int code = 0;
int i = 0;
int[] guesses = new int[7];
System.out.println("Secretly type the code or input -1 if you want me to choose");
input = scanner.nextInt();
if (input == -1) {
code = randomGenerator.nextInt(100);
}
else {
code = input;
}
System.out.println("Start guessing!");
while (i < 7) {
guesses[i] = scanner.nextInt();
if (guesses[i] == code) {
System.out.println("Good guess! You won.");
System.out.println((i+1) +" guesses");
i++;
for (int k=0; k<i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
else if (code < guesses[i] && i != 6) {
System.out.println("lower");
i++;
}
else if (code > guesses[i] && i != 6) {
System.out.println("higher");
i++;
}
else {
System.out.println("No more guesses, you lost");
System.out.println((i+1) + " guesses");
for (int k=0; k<=i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
}
}
}
When you wrap a stream with another (like you do in scanner) closing the stream closes the wrapped streams.
That means you would close System.in if you closed your scanner.
I recommend setting your scanner variable to null, and letting the garbage collector remove it from the heap. Unless you explicitly want to close the input to the program, this will likely have the desired effect.
You should close the scanner after the while loop. Else you will certainly get errors.
use
Scanner scanner = ....;
try {
while () {} ....
} catch (Exception ex) {
try {scanner.close();}catch {} // closes the scanner in case of an exception
} finally { try {scanner.close(); } catch {}} // makes sure that the scanner closes. try catch because it may fail.
I cant reproduce your error with the scanner.close() method but I think it is not working inside a loop. Here is an example with it working for me:
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
int input;
int code = 0;
int i = 0;
int[] guesses = new int[7];
System.out.println("Secretly type the code or input -1 if you want me to choose");
input = scanner.nextInt();
if (input == -1) {
code = randomGenerator.nextInt(100);
}
else {
code = input;
}
System.out.println("Start guessing!");
while (i < 7) {
guesses[i] = scanner.nextInt();
if (guesses[i] == code) {
System.out.println("Good guess! You won.");
System.out.println((i+1) +" guesses");
i++;
for (int k=0; k<i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
else if (code < guesses[i] && i != 6) {
System.out.println("lower");
i++;
}
else if (code > guesses[i] && i != 6) {
System.out.println("higher");
i++;
}
else {
System.out.println("No more guesses, you lost");
System.out.println((i+1) + " guesses");
for (int k=0; k<=i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
}
scanner.close();
}
}

Creating a Palindrome identifier

How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)

Categories

Resources