Hello! Started learning Java recently and having trouble repeating program instructions - java

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");
}

Related

How do I go back to the menu after taking several questions?

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.

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

i want my statement to re-execute if the condition if met false

What I would like to happen here is to have the user input "start". if the user inputs start the program must give a random word from the array and then ask for the user to input "next", when the user inputs "next" the program gives another random word, then the program asks for "next" to be input again and so forth... you get the idea.
here is some code, I thought would produce this effect but all it does is prints "Type start to see a cool word"
user input "start"
and then the program returns nothing.
Any advice would be appreciated and if you could tell me why my code is doing this I would be really appreciative because that way I can learn from this.
Thanks
here is the code i wrote:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate:","Petrichor:"};
String input = "";
System.out.println("type *start* to see a cool word");
input = scan.nextLine();
while(!input.equals("start")){
String random = words[new Random().nextInt(words.length)];
System.out.println(random);
System.out.println();
System.out.println("type *next* to see another cool word");
while(input.equals("next"));
}
}
}
You would like to wrap your input reading in a loop:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate","Petrichor"};
String input = "";
while ( !input.equals("start") ) {
System.out.println("type *start* to begin");
input = scan.nextLine();
}
String random = (words[new Random().nextInt(words.length)]);
}
}
Note that in your particular example the loop conditional works for your if statement so there was no need for the if statement.
Update
If you need to keep this running while the user types next you can wrap everything inside a do .. while loop so it executes at least once:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate","Petrichor"};
String input = "";
do {
do {
System.out.println("type *start* to begin");
input = scan.nextLine();
} while ( !input.equals("start") );
String random = (words[new Random().nextInt(words.length)]);
System.out.println("type *next* to repeat");
input = scan.nextLine();
}
} while ( input.equals("next") );
}

My code isn't working

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.

Why does it not ask me for input?

import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?
You should read your input by using scanner.nextLine():
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next() to read a token scanner.nextLine() to read a line, etc. As well you are comparing a Scanner to a String in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine() to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase for case-insensitive matching too.

Categories

Resources