I made an array to randomly pick either "steak, pizza, or chips" but I upon running my program it errors out well before you even get to the question. It works for about 5 inputs before it gives me an exception.
I assume the problem lies within the
{System.out.println(FoodArray.getRandomWord(args));
but I can't seem to figure out what is wrong with it.
I just need my program to run correctly, and when it gets to the question about giving a random suggestion, it prints out steak, pizza or chips randomly.
public static void main(String[] args) {
int input = 0;
int sweet = 0;
int savory = 0;
int salty = 0;
Random r = new Random();
FoodArray a = new FoodArray();
Scanner myscanner = new Scanner(System.in);
System.out.println("Welcome, lets figure out what you're hungry for."
+ "Press 0 to continue");
input = myscanner.nextInt();
if (input > 0) {
}
{
System.out.println("What sounds the best to you right now?\n"
+ "1) Something sweet\n"
+ "2) Savory\n "
+ "3) Salty\n ");
}
input = myscanner.nextInt();
if (input == 1) {
System.out.println("something sweet. okay. next question");
sweet++;
} else if (input == 2) {
System.out.println("Savory eh? got it. lets move on.");
salty++;
} else if (input == 3) {
System.out.println("Sounds good. Lets proceed");
savory++;
}
System.out.println("Press 0 to continue");
input = myscanner.nextInt();
System.out.println("pick a number 1-3");
input = myscanner.nextInt();
if (input == 1) {
System.out.println("Very interesting.");
sweet++;
} else if (input == 2) {
System.out.println("Very interesting.");
salty++;
} else if (input == 3) {
System.out.println("Very interesting.");
savory++;
}
System.out.println("Press 0 to continue");
input = myscanner.nextInt();
System.out.println("Next question: "
+ "Would you rather, fly, (1) breath underwater, (2) or be invisible (3)");
input = myscanner.nextInt();
if (input == 1) {
System.out.println("Good choice.");
sweet++;
}
if (input == 2) {
System.out.println("Would be pretty cool");
salty++;
}
if (input == 3) {
System.out.println("Trick question, you already are invisible loser."
+ "Lets continue. ");
savory++;
}
System.out.println("Okay. now heres a random suggestion.");
{System.out.println(FoodArray.getRandomWord(args));
}
System.out.println("Okay. Lets see your final score."
+ "Press 0 to continue");
input = myscanner.nextInt();
if (sweet > salty && sweet > savory) {
System.out.println("Get something sweet. maybe cake.");
}
if (salty > sweet && salty > savory) {
System.out.println("Get something salty. Maybe potatoe chips");
}
if (savory > sweet && savory > salty) {
System.out.println("Savory! Steak steak steak!");
}
if (salty == sweet && salty == savory) {
System.out.println("Its a tie. Can't help you. sorry.");
}
if (sweet == salty && sweet == savory) {
System.out.println("Its a tie. Can't help you. sorry.");
}
if (savory == sweet && savory == salty) {
System.out.println("Its a tie. Can't help you. sorry.");
}
}
}
public class FoodArray {
String[] strArray = { "Pizza", "Steak", "Chips" };
static public String getRandomWord(String[] array) {
Random r = new Random();
int index = r.nextInt(array.length);
return array[index];
}
}
change to
::FoodArray::
String[] strArray = { "Pizza", "Steak", "Chips" };
to
public static String[] strArray = { "Pizza", "Steak", "Chips" };
::main::
FoodArray.getRandomWord(args)
to
FoodArray.getRandomWord(FoodArray.strArray)
but this is stupid as FoodArray already knows about strArray so delete the passing of paramaters to this method and use strArray within FoodArray
Related
I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}
I've written a functioning code below and I want to simply change my menu setting from within the program to outside. I've been asked to get the sodaMachine contents from a .txt file from outside the program where the program will take from the .txt file and will display "Take your drink (1.)".
My question is what do I add to get a program that accurate takes int's, and string from a .txt file on command. So if I input "1.)" the program extracts "coca-cola" and its price (an int) "150".
import java.lang.Math;
import java.util.Scanner;
public class CST1201 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int coinTotal = 0;
int coinTotal2 = 0;
int coinTotal3 = 0;
int runAgain = 1;
while(runAgain == 1)
{
while (coinTotal < 100){
System.out.println("Please insert a coin ");
coinTotal2 = input.nextInt();
if (coinTotal2 != 25 && coinTotal2 != 5 && coinTotal2 != 10)
{
coinTotal2 = 0;
while (coinTotal2 != 25 && coinTotal2 != 5 && coinTotal2 != 10)
{
System.out.println("Please insert a coin(5,10,25)");
coinTotal2 = input.nextInt();
if (coinTotal2 != 25 && coinTotal2 != 5 && coinTotal2 != 10)
{
coinTotal2 = 0;
}
else
{
coinTotal = coinTotal + coinTotal2;
coinTotal3 = coinTotal + coinTotal2;
}
}
}
else
{
coinTotal = coinTotal + coinTotal2;
}
System.out.println("Total: " + coinTotal);
}
int choice = 0;
System.out.println("What would you like? \n1.Coca-Cola \n2.Pepsi \n3.Orange Soda \n4.Grape Soda \n5.Mountain Dew \n6.Water");
choice = input.nextInt();
if (choice ==1) {
System.out.println("Please take your Coca-Cola");
} else {
if(choice == 2) {
System.out.println("Please take your pepsi");
} else {
if (choice == 3) {
System.out.println("Please take your Orange Soda");
} else {
if (choice == 4) {
System.out.println("Please take your Grape Soda");
} else {
if (choice == 5) {
System.out.println("Please take your Mountain Dew");
} else {
if (choice == 6) {
System.out.println("Please take your water");
}
}
}
}
}
}
int change;
if (coinTotal > 100){
change = coinTotal - 100;
System.out.println("Please take your change: " + change);
}
System.out.println("Would you like to buy another drink?");
runAgain = input.nextInt();
if (runAgain == 1)
{
coinTotal = 0;
}
else
{
runAgain = 0;
System.out.println("Thank you");
}
}
}
}
I am assuming you want to take as input coinTotal, coinTotal2, coinTotal3, choice, and runagain from a .txt file and run your program multiple times for the given inputs?
If that is the case, you can just put your whole method into a function with the above parameters, and give parameters in a loop through your .txt input file.
You can use File, and Scanner to read the contents from the file depending on how its arranged in the file.
Scanner scan = new Scanner(new File("FileName")); // this gets you your file
You can access elements of file as a 1 word string, using scan.next() and then parse it to your appropriate need, and then pass it on to your function.
Hope that helped.
I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class t1_lesson03_template{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();
if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");
System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");
System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}
}
}
This,
else if (userinput1.equals(answer1) || userinput2.equals(answer2)
|| userinput3.equals(answer3)) {
should be something like
else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
(userinput1.equals(answer1) && userinput3.equals(answer3)) ||
(userinput2.equals(answer2) && userinput3.equals(answer3))) {
but I would prefer a count. And an array to display your different messages. Something like
int count = 0;
if (userinput1.equals(answer1)) {
count++;
}
if (userinput2.equals(answer2)) {
count++;
}
if (userinput3.equals(answer3)) {
count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Just add braces before each condition in if class and else if such as
if ((userinput1.equals(answer1)) && (userinput2.equals(answer2)) && (userinput3.equals(answer3))) {
System.out.println("3/3 Awesome!");
}
else if ((userinput1.equals(answer1)) || (userinput2.equals(answer2)) || (userinput3.equals(answer3))) {
System.out.println("2/3 Good job.");
}
Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement
So I just have a quick little issue
int pickmeup = 0;
while (true)
{
pickmeup = scanner.nextInt();
if (pickmeup == 1)
{System.out.println ("you entered 1");}
if(pickmeup == 2)
{System.out.println ("you entered 2");}
{
break;
}
System.out.println ("Invalid code");
Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.
If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?
I believe you want to use a logical or || and an else like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1 || pickmeup == 2) {
System.out.printf("you entered %d%n", pickmeup);
} else {
System.out.println("Invalid code");
}
}
Alternatively, you could use an else if chain like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1) {
System.out.println("you entered 1");
} else if (pickmeup == 2) {
System.out.println("you entered 2");
} else {
System.out.println("Invalid code");
}
}
You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL+SHIFT+F
For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pickmeup = 0;
while (true){
pickmeup = scanner.nextInt();
if (pickmeup == 1){
System.out.println("one");
}
else if (pickmeup == 2){
System.out.println("two");
}
else{
System.out.println("Invalid code");
break;
}
}