Trouble with while loop and scanner java [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Very new to programming. I know this question will be very easy to answer for experienced programmers. I would like to continue running this program which finds leap years until the user enter "n." The program terminates before being able to enter y/n. Help is very much appreciated... thank you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String another = "y";
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a year ");
int year = scan.nextInt();
while (another.equals("y")) {
if (year < 1582) {
System.out.println("Not an established Gregorian year.");
} else if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)) {
System.out.println("Not a leap year");
} else {
System.out.println("Leap year!");
}
System.out.println();
System.out.print("Test another year (y/n)?");
another = scan.nextLine();
}
}
}

The enter from when the person enters the year number at the beginning is not used up. It is stored in the "buffer" and when the program reaches the point where you ask if they want to do another year, it reads the enter that is in the buffer. To fix this you just need another scan.nextLine(); before the important one.

Related

How will I loop this java program with Question of "Do you want to Try Again?! [Yes/No]"? [duplicate]

This question already has answers here:
How do I make my code run in a loop and ask the user "Try again Yes or no?"
(4 answers)
Closed 3 years ago.
I'm new on this java programming. And I need to make this program loop
the Question "Do you want to Try Again?! [Yes/No]" and loop it back to
"Enter any year:" question. How will I do that?
I hope you provided me with more elaborated answer or example to make this program work properly within today..
import java.util.Scanner;
public class my_LeapYear {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter any year: ");
int year = s.nextInt();
boolean loop = true;
while(loop == true)
{
if (((year %4==0)&& (year %100 !=0))||(year %400==0))
{
System.out.println("Year "+year+" is a Leap Year");
break;
}
else if ((year %100 == 0)&&(year %400 == 0))
{
} else {
System.out.println("Year "+year+" is not a Leap Year");
loop = false;
break;
}
Try to use if statement that checks whether yes or no is entered , update the value of loop accordingly see below
System.out.println("Do you want to Try Again")
String input = in.nextLine();
if (input.equals("YES")){
loop = true
}
else if (input.equals("NO")){
loop=false
}

NoSuchElementException, when method is called after code above it is run [duplicate]

This question already has answers here:
Scanner close after use
(2 answers)
Closed 3 years ago.
When I run my code, it will run fine up to the line "scanner.close()".
After than, when I run the "SumTenNumbers()" method... it will run the first line of the while loop once and crash with the "NoSuchElementException"...
When I remove the code above the line calling the method, it runs fine...
Why does this occur, and how can I solve it?
This is the code:
public class Main
{
public static void main(String[] args)
{
// we use the class "scanner" for input data
Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Your name is " + name);
System.out.println("Enter your year of birth: ");
boolean isInt = scanner.hasNextInt();
if (isInt)
{
int yearOfBirth = scanner.nextInt();
int age = 2019 - yearOfBirth;
if (age >= 0 && age <= 120)
{
System.out.println("You are " + age + " years old");
}
else
{
System.out.println("Invalid year of birth");
}
}
else
{
System.out.println("Unable to parse year of birth");
}
scanner.close(); // we must close scanner
SumTenNumbers();
}
public static void SumTenNumbers()
{
var reader = new Scanner(System.in);
int sum = 0;
int count = 1;
while (count < 11)
{
System.out.println("Enter number " + count + ": ");
boolean valid = reader.hasNextInt();
if (valid)
{
int userNum = reader.nextInt();
sum += userNum;
count++;
}
else
{
reader.next();
System.out.println("INVALID");
}
}
System.out.println(sum);
reader.close();
}
}
This is how it looks when I run the code...
Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at com.company.Main.SumTenNumbers(Main.java:64)
at com.company.Main.main(Main.java:39)
Process finished with exit code 1
the line reader.close() closes the Scanner and, with it, System.in.
After that, you cannot read from stdin (System.in) anymore.
In order to prevent this you can:
use only one Scanner object and close it after using it the last time
close System.in after using it the last time (using a Scanner or System.in.close())
close System.in at the end of your Program
never close System.in (Problem: other Processes cannot use the resource, stdin can also be a File, a Network Connection or something else)

If else statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Want to have this code to search for dates between 1950-2050 and find out when Nothing happened, World cup, Olympic games or the info you write does not match any of the dates.
So the OL occurs when the number between 1950-2050 is divided by 4. And the WC occurs between even years of the OL like 2002(2004 WC)2006.
Then we have the dates no OL/WC occur between 1950-2050, that year nothing happened. And last if you put in like 700 it should just say the last else.
Scanner input = new Scanner(System.in);
System.out.println("Write year between 1950-2050: ");
int keyboard = input.nextInt();
int OL = (keyboard);
int WC = (keyboard);
int nothingspec = (keyboard);
int instru = (keyboard);
if(nothingspec) {
System.out.println("This year nothing special happened.");
}
else if(OL) {
System.out.println("Yes this year it the olympic games. ");
}
else if(WC) {
System.out.println("Yes this year it was a world cup in soccer.");
}
else(instru) {
System.out.println("Your instructions were wrong please try again.");
}
input.close();
As much as i understand it should be something like this
System.out.println("Write year between 1950-2050: ");
int keyboard = input.nextInt();
int OL = (keyboard);
int WC = (keyboard);
int nothingspec = (keyboard);
int instru = (keyboard);
boolean blOL = false;
boolean blWC = false;
//this occurs whenever the number can be divided by 4
if(keyboard>=1950&&keyboard<=2050){
if(OL%4==0) {
System.out.println("Yes this year it the olympic games. ");
blOL=true;
}
//This will happen every time the date can be divided to 2 so as you said 2002, 2004, 2006 and so on.
else if(WC%2==0) {
System.out.println("Yes this year it was a world cup in soccer.");
blWC = true;
}
//This is when nothing has happend.
else if(blOL==false && blWC==false) {
System.out.println("This year nothing special happened.");
}
else{
System.out.println("Your instructions were wrong please try again.");
}
}
else{
System.out.println("Your instructions were wrong please try again.");
}
input.close();
Please try this and tell me if this is what you needed.

Why won't this If statement work for the string? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
import java.util.Scanner;
public class Methods {
/*
* Compound interest Program Quarterly
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("What is the Rate");
int rate = keyboard.nextInt()/100;
System.out.println("What is the Amount");
int amount = keyboard.nextInt();
System.out.println("How many years?");
int years = keyboard.nextInt();
keyboard.nextLine();
System.out.println("How is it compounded? Press Q = Quarterly, A = Anually, S = SemiAnnualy, M = Monthly");
String answer = keyboard.nextLine();
int easy = amount*(1+(rate/years));
int pow = 4 * years;
if (answer == "/Q"){
System.out.println("Your answer compounded Quarterly is: " + Math.pow(easy,pow));
This is the code, but the if statement with String == "Q" doesn't work because when I press Q nothing happens? what's the issue?
Java right? use equalsIgnoreCase because you could be typing 'q' and that / they told you about too, keep it in mind
Maybe you can try
if(answer.equals("Q"))
First issue is that you have a typo (the forward slash) in this line:
if (answer == "/Q"){
The second issue is that you don't compare strings like this.
Instead use the "equals()" method.
if(answer.equals("Q")){
See here for more information: How do I compare strings in Java?

How to reach a desired point in the code in java? [duplicate]

This question already has answers here:
How to repeat/loop/return to a class
(4 answers)
Closed 8 years ago.
I want to make a logic of getting grades. I proceed in a way of getting total marks as input from user using the Scanner class, then I'm validating marks if it is between 0 and 100(both inclusive).
Now if the marks are not in between this range, I print "Enter valid marks!!", and I want it to go to previous step and ask for the input from user again.
import java.util.Scanner;
class Performance
{
public static void main(String[] aa)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
}
// Now if this condition is true then I want the control to go again to line 7
// Please suggest me the way to Proceed
}
}
Please suggest the way to proceed with the modification in the above code.
See this link.
You want to do something like that:
do {
code line 1;
code line 2;
code line 3;
} while(yourCondition);
Now, if yourCondition is satisfied, the code will go to code line 1 again (will perform the code block between do and while).
Now, after you understand how it works, you can easily apply this to your task.
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
} else
break;
} while (true);
Try this:
boolean b = true;
while(b){
if(marks<0 || marks>100){
System.out.println("Enter valid marks!!");
marks= scnr.nextInt();
}
else{
b= false;
//Do something
}
}
8 int marks = scnr.nextInt();
9 while(marks<0 || marks>100)
10 {
11 System.out.println("Enter valid marks!!");
12 System.out.println("Enter the marks :");
13 marks = scnr.nextInt();
14 }
Thanks Guys for your help.
FInally i proceeded in the way as follows:
public static void main(String[] aaa)
{
int counter=0;
Scanner scnr = new Scanner(System.in);
int marks;
do
{
counter++;
System.out.println("Enter the marks :");
marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Marks entered are not valid");
if(counter>=3)
{
System.out.println("You have exceeded the maximum number of attempts!!");
System.exit(1);
}
else
System.out.println("Enter valid marks!!");
}
else
break;
} while(true);
}

Categories

Resources