I am currently creating a program where the user enters a specific set of questions. And the program must go back to the menu after completely answering all questions. How should I do it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("""
\n \nAre you ready to take the quiz?
Enter "Y" to proceed or "N" to exit the program:""");
String TakeQuiz = input.nextLine();
if (TakeQuiz.equalsIgnoreCase("Y"))
do {
//blocks of code
}
}
}
System.out.println("Do you want to take the quiz again?");
String RetakeQuiz = input.nextLine();
while (RetakeQuiz.equalsIgnoreCase("Y")) ;
else {
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
There are many ways to achieve what you want, I would not clutter the main method and break the code to another function and loop there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for(;;)
takeQuiz();
}
public static void takeQuiz(){
Scanner input = new Scanner(System.in);
System.out.print("\n \nAre you ready to take the quiz?" +
"Enter \"Y\" to proceed or \"N\" to exit the program:");
String takeQuiz = input.nextLine();
if (takeQuiz.equalsIgnoreCase("Y")) {
System.out.println("Running code...");
System.out.println("Question 1");
System.out.println("Question 2");
System.out.println("Question 3");
}
// retake
if (takeQuiz.equalsIgnoreCase("R")){
takeQuiz();
}
if (takeQuiz.equalsIgnoreCase("N")){
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
Notice the escape character for quotes \" and the + for multiline Strings
Java 15 and beyond allows triple quotes as Java Text Blocks
so your String message should be valid
The basic structure is something like this:
boolean continueWithQuiz = true;
while (continueWithQuiz) {
// Put the code here for handling the quiz
...
// Should we keep going?
System.out.println("Do you want to take the quiz again?");
String retakeQuiz = input.nextLine();
continueWithQuiz = retakeQuiz == "Y";
}
One more comment. Please follow Java naming standards. Class names begin with an upper case letter. Constants should be ALL_CAPS. Everything else is in lower case.
Related
import java.util.Scanner;
public class HelloWorld {
public static int num;
public static Scanner scan;
public static void main(String[] args) {
System.out.println("Hello World");
/* This reads the input provided by user
* using keyboard
*/
scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
check();
// Closing Scanner after the use
// Displaying the number
System.out.println("The number entered by user: "+num);
}
public static void check(){
try{
num = scan.nextInt();
}
catch (Exception e){
System.out.println("not a integer, try again");
check();
}
}
}
Im new to coding, and am taking this summer to teach myself some basics. I was wondering if someone could advise me on how I can create this method to take in a int, and check the input to make sure thats its a int. If the input is not a int, I would like to re run in.
Simple. Say you have something as shown below . . .
NumberThing.isNumber(myStringValue);
.isNumber() determines if your string is a numerical value (aka a number). As for putting the code in a loop to continue to ask the user for input if their input is invalid, using a while loop should work. Something like . . .
while (. . .) {
// use something to exit the loop
// depending on what the user does
}
You might consider moving the user request code to the check method. Also, use a break statement to exit your while loop after a valid number is entered.
while ( true )
{
System.out.println( "Enter an integer.");
try
{
num = scan.nextInt();
break;
}
catch (Exception e)
{
System.out.println("not a integer");
}
}
I am a beginner programmer and i am trying a program for my father.
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee
{
String m1,m2,m3,m4,m5,m6,m7;
void main()
{
Scanner w=new Scanner(System.in);
Scanner n=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=n.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
This Code will give the output "as you have entered a wrong choice'"
It jumps to elsse statement. What is the error and is there an easier way to run this program. Thanks
Could yo please inform me on my error as
Ok try this code:
import java.util.Scanner;
public class Try
{
static String m1,m2,m3,m4,m5,m6,m7;
public static void main(String[] args)
{
Scanner w=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=w.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
You have missed you main method signature. In Java there is a specification of main method. Your main method should be like
public static void main(String []args){
}
In your case you main method should be
public static void main(String args[]) {
String m1, m2, m3, m4, m5, m6, m7;
Scanner w = new Scanner(System.in);
Scanner n = new Scanner(System.in);
System.out.println("Please enter your name ");
String name = w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client = n.nextInt();
m1 = name;//Storing name
if (client == 1)//If statement storing client
{
m2 = "XXXXXX";
} else {
System.out.println("You have entered a wrong choice");
return;
}
String msg = m1 + "\t" + m2;
System.out.println(msg);
}
Your problem are the 2 scanners.
Because a scanner work with an iterator, that keep the position inside the given inputstream (in this case), when you instantiate the 2 scanners, they both set their iterator at the same position into the stream, then you use "w.nextLine();", and the first scanner advances trough the stream returning the first line, as you wish, but the second scanner, that you haven't used, is still at the beginning of the stream, so basically when you use n.nextInt();, the scanner tries to parse your name as int, and it's strange that it doesn't throws an InputMismatchException, as it should do ("https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29").
Rework your code as #Sarthak Mittal suggested and it should work.
PS: keep in mind indentation, it's important, really
First:
void main()
There is no such thing in Java. It should be,
public static void main(String[] args)
To know the meanings of public, static, String[] args read this: Explanation of 'String args[]' and static in 'public static void main(String[] args)'
Secondly,
int client = n.nextInt();
The value inside client depends on your input. If you input 2 or 3 instead of 1, your code'll definitely go to the else part. So make sure your input is 1.
Thirdly,
Get rid of the extra scanner. You need only one.
The rest of your code is ok.
So I tried out having a password check in my program, the goal is, if the user types the correct password then the program will reply: "You Pass", if not the "You're wrong". The problem is Eclipse tells me that "Fish (that's the password) cannot be resolved to a variable"
import java.util.Scanner;
public class Password {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
I tried resolving the issue in Eclipse's way, but with their method I get the wrong password when I type it after running the program:
import java.util.Scanner;
public class Password {
private static final String Fish = null;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
I tried looking this up online, I'm actually reading Java Programming for Dummies, and still no luck, hopefully you can help me, I'd appreciate it!
Thanks!
You have wriiten some wrong syntaxes for it.Try this code.I have added necessary comments to let you make undersatand that what I have done in the following code.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = "Fish"; // assigning value to String password
System.out.println("enter value");
String temp=scan.nextLine(); //scanner takes nextline entered and assign it to temp
// if (scan.equals(password)) is wrong ,you want to compare value taken by scanner , what you have wriiten is incorrect. scan is object of Scanner.Not value taken by it
if(temp.equals(password)) //if entered value eqauls your assigned password value
{
System.out.println("You pass!"); // else print you pass
}
else
{
System.out.println("You're wrong!"); //else print "you are wrong"
}
First of all,you're never reading your input in a variable!and then you're trying to check equality between the "scan" object which is of type Scanner.Instead read input "scan.nextLine();" in a variable say "var" and then call var.equals(password).Please also check that your String "Fish" is null initially which will give you a NullPointerException!
if (isValid(password))
{
System.out.println("You pass!");
}
else
{
System.out.println("You're wrong!");
}
Welcome to the Java World!
In your program you are making a small mistake by calling the equals on a Scanner object.
Also remember to close the close-able scanner resource once you are done with it.
Please refer the code below.
import java.util.Scanner;
public class Password {
private static final String Fish = "Fish";
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("What is the password? ");
if (scan.nextLine().equals(Fish)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
I am new to Java and programming outside of VB in general and I am looking for some basic help.
I wrote the following code below and I want the program to repeat until the user types stop.
import java.util.Scanner;
public class lame
{
public static void main (String args[])
{
System.out.println("Welcome to robo lame tester 1.1, is your name Connor? Yes or no?");
Scanner input = new Scanner(System.in);
String sweg = input.nextLine();
if (sweg.equals("Yes"))
System.out.println("You are lame");
else
System.out.println("You passed, you aren't lame");
}
}
I typed this in real quick... but it should do what you ask. So I added a while true that would make it loop forever. The while(condition) statement will loop until condition is given a false statement. The other way to leave would be to break the loop with the break statement or the return statement (as I did in there). break will make you leave the loop and return will make you leave the method.
import java.util.Scanner;
public class Lame {
public static void main (String args[])
{
while(true) {
System.out.println("Welcome to robo lame tester 1.1, is your name Connor? Yes or no?");
Scanner input = new Scanner(System.in);
String sweg = input.nextLine();
if(sweg.equals("stop"))
return;
if (sweg.equals("Yes"))
System.out.println("You are lame");
else
System.out.println("You passed, you aren't lame");
}
}
}
Insert it in a loop, as this:
import java.util.Scanner;
public class Lame {
public static void main( String args[] ) {
String sweg = "";
do {
System.out
.println( "Welcome to robo lame tester 1.1, is your name Connor? Yes or no?" );
Scanner input = new Scanner( System.in );
sweg = input.nextLine();
if ( sweg.equalsIgnoreCase( "Yes" ) ) {
System.out.println( "You are lame" );
} else if ( sweg.equalsIgnoreCase( "no" ) ) {
System.out.println( "You passed, you aren't lame" );
}
} while ( !sweg.equalsIgnoreCase( "stop" ) );
System.out.println( "Bye!" );
}
}
Adendum
Class names begin with a capital by convention in Java. String's equalsIgnoreCase is recommended for user input, so they don't need to maintain the case.
Here is how
Scanner input = new Scanner(System.in);
String sweg = null;
while(!((sweg =input.nextLine()).equals("stop"))){
System.out.println("you are lame");
}
"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...