Having trouble adding a for loop to program - java

I'm having trouble adding a for loop into my older program. I have to make it so at the end the user has an option to ask the question again. This is what I have so far
Also just started learning for loops sorry if the question is stupid
http://gyazo.com/a71e2a0b06ed41c47d62ccc05d8ffec8

Your question isn't stupid, I think you just have the wrong idea here.
Anyways, here's your code, editable, and copyable
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years: ");
int age = scan.nextInt();
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
}
}
/*
this is the code you had trouble including
for(int age = scan.nextInt(); int dogAge = age * 7; i++);
{
System.out.print("Enter your dog's age in human years: ");
}
*/
Anyways, so that's your code. All you ever need to do is copy paste, and then highlight all the code, then press the 2 brackets symbols in the little box above the text field.
Now, as to your actual question, a simple way to make all this possible would be, throw that for loop around everything that you want the program to repeat (and a method I added in to ensure it's numeric), here is what I mean.
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years. ");
int age = scan.nextInt();
for(int i = 0; i < 10000; i++)
{
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
System.out.print("Enter your dog's age in human years. (Enter a negative number to stop the program)\n");
String response = scan.next();
age = Integer.parseInt(response);
if(age < 0)
{
i = 10001;
}
}
}
}

Related

In my code, you can set a score for 1 test, but I need for three tests

I need to modify my code . So that the user enters the number of students and their grades on three tests, and the program writes to him how many students have entered the institute (passing score = 7, maximum score = 10). I wrote the code for one test and don't know how to write for three.
This problem is under the comment: "//Information input and calculation"
import java.util.Scanner;
public class Attestation {
static double InputNumber(String caption) {
System.out.print(caption);
Scanner sc = new Scanner(System.in);
boolean IsError;
do {
IsError = !sc.hasNextDouble();
if (IsError) {
System.out.print("ERROR: ");
sc.nextLine();
}
} while (IsError);
return sc.nextDouble();
}
public static void main(String[] args) {
// Entering quantities of numbers
int count = (int) InputNumber("enter the number of students: ");
// Header
System.out.println("Test №1\t │ Test №2\t │ Test №3");
System.out.println("---------------------------------------------");
// Information input and calculation
int passed = 0;
for (int i = 1; i <= count; i = i + 1) {
double number = InputNumber("enter the grades of the " + i + " student: ");
if(number >= 7) {
passed = passed + 1;
}
}
// Displaying information
System.out.println("---");
System.out.println(passed + " students entered the institute");
}
}
I tried to modify the code, but I was constantly getting an error

combining several if statement for one input in java

im begginer in java , could anyone tell me how to combine several if in one input.
I mean something like this "
how old are you?"
when user answer this it works with several if forexample my code is :
public static void main(String[] args) {
int age = 40;
Scanner ageField = new Scanner (System.in);
System.out.print("How old are you? ");
if(ageField.nextDouble() > age ){
System.out.print("you are over than 40 years old");
}else if(ageField.nextDouble() < age ){
System.out.print("you are less than 40");
}else if(ageField.nextDouble() < 20 ){
System.out.print("you are less than 20");
}else {
System.out.print("enter your age");
}
}
}
i mean the answer should based on the given value,hope you get what im saying
Your code is not working because you are discarding the user input ate checking the 1st conditional if...
Store the user input (which BTW should be an integer instead of a double)
ageField.nextInt()
In a variable and use that in the if else conditions... no need to call get Double several times
Here's actually one of possible optimization OP has asked for. One if statement that can be reused as much as needed. The program will ask for input for the number of your items in ages list:
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args) throws IOException
{
List<Integer> ages = Arrays.asList("20", "40").stream().map(Integer::valueOf).collect(Collectors.toList());
try (Scanner ageField = new Scanner(System.in))
{
System.out.print("How old are you? ");
ages.forEach(e -> analyzeAge(ageField.nextInt(), e));
}
}
private static void analyzeAge(int ageInput, int ageCompared)
{
String answer = null;
if (ageInput > ageCompared)
{
answer = "You are older than " + ageCompared;
}
else if (ageInput < ageCompared)
{
answer = "You are younger than " + ageCompared;
}
else
{
answer = "You are exactly " + ageCompared + " years old";
}
System.out.println(answer);
}
}
Your code will not work because you are calling nextDouble() several times. Instead, store the age variable in an int and perform your if statements against this age variable.
Scanner sc = new Scanner (System.in);
System.out.print("How old are you? ");
int age = sc.nextInt();
if(age > 40){
System.out.print("You are more than 40");
}else if(age < 40 && age >= 30){
System.out.print("You are less than 40");
} else if(age < 30) {
System.out.print("You are less than 30");
}
....

Program crashes when trying to catch exception

I'm trying to make a method that gets the user's input of 6 numbers and add them to a Tree set of integers. I'm trying to make a try and catch exception so if the users accidentally enters in a letter it'll catch the exception and ask them to enter in a number. Right now the program crashes when you try to enter in a letter. It'll print out "Invalid" then crashes. I'm not sure whats going on. Can anyone provide some insight?
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
for (int i = 0; i<6 ; i++)
{
try
{
System.out.print(i+1 + ": ");
userInput = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Invalid");
userInput = input.nextInt();
}
getNumbers.add(userInput);
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Just a few notes on some of the changes made. From your original code, one thing I noticed that is not really an error but a head scratcher. Both of your methods (getWinning Numbers() and getTicket() ) returned a Set<integer> set, however you did not use it in main. So I simply took the output from the methods and placed them in the main method, where they should be IMHO. Methods like these should do ONE thing and in this case is return a set of integers. No printing or anything else that’s all it does.
I changed the logic in the getTicket() method. I simply set up a loop that continued until you had 6 valid numbers. Inside that loop I use a try statement to weed out the invalid input. The way the try statement is set up is one of many ways that you could accomplish this. As you can see the statement immediately after the try (guess = Integer.parseInt(userInput);) is where the invalid input problem could pop up and throw a NumberFormatException. If the input is invalid, you drop immediately to the catch where we output a message and continue. If the input is valid then we simply check for duplicates and the range of the number. If the numbers are ok then add it to pickedNumbers and increment numberCount.
public class Lottery
{
public static Set<Integer> generateWinningNumbers()
{
Random rndNumbers = new Random();
TreeSet<Integer> winningNumbers = new TreeSet<Integer>();
int max = 40;
int min = 1;
int range;
int sixNum;
for (int i = 0; i < 6; i++)
{
range = max - min + 1;
sixNum = rndNumbers.nextInt(range) + min;
while (winningNumbers.contains(sixNum))
{
sixNum = rndNumbers.nextInt(range) + min;
}
winningNumbers.add(sixNum);
}
return winningNumbers;
}
public static Set<Integer> getTicket(Scanner input)
{
String userInput;
int guess;
TreeSet<Integer> pickedNumbers = new TreeSet<Integer>();
System.out.println("Enter your 6 numbers between 1-40: ");
int numberCount = 1;
while(numberCount < 7)
{
System.out.print(numberCount + ": ");
userInput = input.nextLine();
try
{
guess = Integer.parseInt(userInput);
if( guess > 0 && guess < 41 && (!pickedNumbers.contains(guess)) )
{
pickedNumbers.add(guess);
numberCount++;
}
else
{
if (pickedNumbers.contains(guess))
{
System.out.println("Number already picked: " + guess);
}
else
{
System.out.println("Invalid number. Pick a number between 1-40: " + guess);
}
}
}
catch (NumberFormatException e)
{
// bad input
System.out.println("Invalid input: " + userInput);
}
}
return pickedNumbers;
}
}
Changes in the Main now take advantage of the methods returning a Set of integers for us. We create two Set<Integer> variables (winningTicket and userTicket) then we simply get the returned sets from the methods and output the results as opposed to printing the results from the methods.
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
boolean done = false;
String yesNo;
Set<Integer> winningTicket;
Set<Integer> userTicket;
while(!done)
{
winningTicket = Lottery.generateWinningNumbers();
userTicket = Lottery.getTicket(userInput);
System.out.println("Your ticket was: " + userTicket);
System.out.println("Winning Numbers: " + winningTicket);
System.out.print("\nWould you like to try again? ");
yesNo = userInput.nextLine();
if(!yesNo.equalsIgnoreCase("y"))
{
System.out.println("Done");
done = true;
}
}
userInput.close();
}
Hope this helps
This happens because you don't catch exceptions inside cath block. for loop doesn't look good here, try while:
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
int correct = 0;
while(correct < 6)
{
try
{
System.out.print((correct+1) + ": ");
userInput = input.nextInt();
getNumbers.add(userInput);
correct++;
}
catch (InputMismatchException e)
{
System.out.println("Invalid input");
}
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Also you cant't print collection that simple:
System.out.println("Your ticket was: " + getNumbers);
What you can do, is to use streams:
System.out.println("Your ticket was: " + getNumbers.stream().map(Object::toString).collect(Collectors.joining(" ")));

How to validate string from user input to pre defined name [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
Hello all I am trying to write a loop in my code that would prompt user if they enter something other than what I have predefined. I am somewhat familiar with this done to user input that is not specific word or int but not sure when user has three choices to choose from.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// this class will instantiates player object
public class Adventure {
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
List<String> names = Arrays.asList("mage","archer","warrior");
String userinput;
while (myinput.hasNext()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "
+ gameplayer.getClassName()+ ". What health do you have?");
}
}
int healthofPlayer ;
while (myinput.hasNextInt()){
healthofPlayer = myinput.nextInt();
if ((!myinput.hasNextInt())){
System.out.println("I'm sorry, what was that?");
}
else {
gameplayer.setHealth(healthofPlayer);
System.out.println("Very good. Now let's get started on your adventure.");
System.out.println("You awake alone, disoriented, and locked in the CS1331 TA Lab.");
}
return;
}
}
}
try out this, it should work out the rest.
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
List<String> names = Arrays.asList("mage","archer","warrior");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String userinput;
while (myinput.hasNext() || myinput.hasNextInt()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "+ gameplayer.getClassName()+ ". What health do you have?");
int numberofHealth = myinput.nextInt();
}
System.out.println("Very good. Now let's get started on your adventure.");
gameplayer.setHealth(numberofHealth);
return;
}
}
There's no need loop for this. It'll be easier to delegate to a function as you'll see.
List<String> acceptable = Arrays.asList("mage", "archer", "warrior");
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
gameplayer.setclassName(promptFor(acceptable));
// having a function for this encapsulates the looping and the checking
// as well as the reprompting - it also means we can leave the loop
// with the right answer
String promptFor(Set<String> acceptable) {
while(true) { // while true sucks, but you've asked for an indefinite loop
String next = myinput.next().toLowerCase();
if (acceptable.contains(next)) {
return next;
}
// so it was a bad input
System.out.println("I'm sorry, what was that?");
} // loop some more
return null; // unreachable code
}

why does this code not let me input a command after the calculator class is done?

I am trying to make a simple text based operating system and I cant figure out why my code doesn't let me enter a command after the calculator class is done. It is supposed to continue executing the code until I type "off" but this is not the case. Eclipse says it is running but I cant do anything. can someone please help me?
here is my two classes:
public class Calculator extends Start{
public static void calStrt() {
System.out.print("\nEnter operator you wish to use: ");
StringInput = scan.nextLine();
if (StringInput.equals("+")) {
add();
} else if (StringInput.equals("-")) {
sub();
} else if (StringInput.equals("*")) {
mul();
} else if (StringInput.equals("/")) {
div();
} else {
System.out.println("\nSyntax error: Operator not recognized");
System.out.println("Please try again");
calStrt();
}
}
public static void add() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 + intVar2));
}
public static void sub() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 - intVar2));
}
public static void mul() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 * intVar2));
}
public static void div() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 / intVar2));
}
}
import java.util.Scanner;
class Start {
static Scanner scan = new Scanner(System.in);
static String StringInput;
static int intInput;
public static void main(String[] args) {
System.out.println("\nWelcome to RobOS");
passLoop: while (true) {
System.out.print("\nPlease enter password: ");
StringInput = scan.nextLine();
if (StringInput.equals("banana")) {
System.out.print("Logging in, please wait");
System.out.print(".");
System.out.print(".");
System.out.println(".");
System.out.println("\nWelcome User");
outerLoop: while (true) {
System.out.println("\nType \"help\" to see a list of programs");
StringInput = scan.nextLine();
innerLoop: while (true) {
if (StringInput.equalsIgnoreCase("cal")) {
Calculator.calStrt();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("guess")) {
GuessGame.guess();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("help")) {
System.out.println("\n\"cal\" uses the calculator");
System.out.println("\"guess\" plays guessing game");
System.out.println("\"help\" shows list of programs");
System.out.println("\"off\" turns RobOS off");
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("off")){
break passLoop;
}
}
}
} else {
System.out.println("\nWrong password. Please try again");
continue passLoop;
}
}
}
}
Brent Nash is correct. To fix the error though, try using instead of scan.nextInt(): Integer.parseInt(scan.nextLine());
Hope this works
Your code is getting into an infinite loop. When you call StringInput = scan.nextLine(), the first time it works fine. I entered cal and I can run the calculator once. The problem is that the second time scan.nextLine() gets called, it's automatically returning an empty string "" as the value of StringInput. Your set of if/else statements in the while(true) have no way to handle this, so it just loops forever.
The deeper rationale is that you call scan.nextInt() to read in the numbers, but the problem is when you read in the second number for the calculator operation, there's still a "\n" sitting on System.in. As a result, when you loop around and call scan.nextLine() again, it doesn't prompt you for anything because it just reads that "\n" that's still sitting on System.in and then that sends you into an infinite loop.

Categories