I am trying to bring in some numerical values by way of Scanner(System.in). I am calling a class with my method from main and having a difficult time exiting the method, my questions are looping.
I am sure this is a simple issue but I am having a heck of a time finding a solution.
Here is the method:
public static Object userInput(double nutWidth, double lastFretWidth, double scaleLength, int numFrets) {
boolean dataCheck = true;
try {
while (dataCheck == true) {
System.out.println("What is the width at the nut?");
NutWidth = key.nextDouble();
System.out.println("What is the width at the last fret?");
LastFretWidth = key.nextDouble();
System.out.println("What is the scale length?");
ScaleLength = key.nextDouble();
System.out.println("How many frets will your guitar have?");
NumFrets = key.nextInt();
dataCheck = false;
}
} catch (InputMismatchException e) {
System.out.println("Enter a integer.");
key.nextInt();
}
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
}
Here is my main:
public static void main(String[] args) {
FingerBoard.userInput(0, 0, 0, 0);
FingerBoard.UserData();
}
Any help is greatly appreciated-Mike
You have written an infinite recursion. The line
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
will call the same method again after finishing the previous method. It looks to me like you want to store the values in a data structure and return that, which would require calling a constructor something like this:
return new UserInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
You would have to write the data structure UserInput yourself. If you haven't gotten to writing classes and data structures yet, you probably want your variables to be static fields. If you are doing that, change the return type to be void and remove the return statement entirely.
Additional comments not related to your problem. You don't need the arguments to your method. They are never used. You probably also want to put the try/catch inside of the while loop. That way an invalid input will prompt for new input, rather than setting things to 0.
Related
Literally started with Java today, and my professor has given my class the task of modifying some very basic code.
I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. I have no idea why. Please help.
import java.io.Console;
import java.util.Scanner;
public class FirstProgram{
Console t = new Console();
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
int n1, n2;
Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt( );
n2 = keyboard.nextInt( );
//This should print normally when the sum is anything BUT 666
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
//If the sum IS 666, I don't want it to print the above lines, just the one below.
if (n1 + n2 == 666);
t.println("Nice try, Satan");
}
}
It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. I have no idea what any of that means or how to fix it.
You should learn how to make conditional statements. Java will not "ignore" and pass to another thing if you don't tell it how to do that. Remeber: computer can't do anything if one do not tell it to do and how to do that.
You are not initializing n1 and n2, they should be initialized after getting the value from the input.
And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces.
import java.util.Scanner;
public class FirstProgramm{
public static void main(String[] args){
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt( );
int n2 = keyboard.nextInt( );
//See? the result is stored inside this variable
int sum = n1 + n2;
//If the sum is equal 666 then print the message
if(sum == 666) {
System.out.println("Nice try, Satan");
}else {
//Else if the sum is something else, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}
}
}
You can even play with the operator that the if uses to evaluates the condition:
if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}else {// But if it is 666, print what is inside the parentheses
System.out.println("Nice try, Satan");
}
I will try to help you out here.
Firstly: the constructor Console() is not visible
I think this is in reference to the fact that Console was not really meant to be accessed like that. The constructor of Console is private, meaning that outside classes cannot access it. To remedy this issue, when you want to print to the console, use System.console.
Secondly: I cannot make a static reference to a non-static field t
This one is a bit difficult to explain to someone new. Your main function is static, which means it can be accessed without having to instantiate the class that contains it. Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. However, because the main function is static, you cannot access a non-static variable, because it may not be initialized yet. If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible.
Lastly
To getting your code working, you need to read up on if statements. This is a conditional statement that is basically asking if this statement is true, do this. There is an else if and else statements as well that say else if this statement is true, do this and else do this.
Example of proper if/else if/else statement:
if(iAmTrue == true)
{
//do this
}
else if(theOtherIAmTrue == true)
{
//do this
}
else
{
//do this because everything else was not true
}
So to fix your code, you would need to do this:
if(n1 + n2 == 666)
{
System.out.println("Nice try, Satan");
}
else
{
//Put your other print message(s) here.
}
I have rewritten the code for you with a few recommendations to achieve what you need.
import java.util.Scanner;
public class FirstProgram {
// I have removed the Console variable, you don't need that.
// System.out.println prints to the console.
// Use constants for any number or string used to give them meaning
private static final int DEVILS_NUMBER = 666;
public static void main(String[] args) {
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
// declare variables next to where they are used.
// additionally, never declare more than one variable per line.
// never do this: int n1, n2;
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
// store the sum in a variable so you can refer to it without doing the sum many times
int sum = n1 + n2;
//If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
// always test the positive possibility first, never the negation
if (DEVILS_NUMBER == sum) {
System.out.println("Nice try, Satan");
} else {
//This should print normally when the sum is anything BUT DEVILS_NUMBER
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
}
}
Last but not least, have a look at Java Google Style for tips on how to properly format your code. If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you.
I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions
New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.
This question already has answers here:
JUnit: How to simulate System.in testing?
(9 answers)
Closed 7 years ago.
Below is the java program to guess the number of Apples Tom has. Tom would type higher if he has higher number of apples than the guessed number and lower if it is lower. He will respond with none when the number guessed is correct. My task is to write a JUnit test case for this program. Since based on the user input the guessed number is either decremented or incremented until we reach the actual value it confuses me as to how to write a JUnit test case for this program
public static void main(String args[]){
System.out.println("Guess the number of Apples Tom has");
Scanner sc= new Scanner(System.in);
int number=sc.nextInt();
System.out.println("Tom, is it higher or lower?");
String higherOrLower=sc.nextLine();
while(true){
number= getValue(higherOrLower,number);
System.out.println("Tom, is it higher or lower?");
higherOrLower=sc.nextLine();
if(higherOrLower.equalsIgnoreCase("none")) {
break;
}
}
}
public static int getValue(String i,int j){
if(i.equalsIgnoreCase("lower")) {
j--;
return j;
} else if(i.equalsIgnoreCase("higher")) {
j++;
return j;
} else {
return j;
}
}
Ok, let's go into a bit of detail here...
The basic for a good unit test is good code. Which explains why writing unit tests doesn't only make code work more reliable, it also tends to make the coders write better code (because bad code if very often hard to test).
In your example you have two methods (I assume you aren't into the details of Object Oriented Programming (OOP) yet, so I will not go into how to structure your code even better with additional classes).
One method does the actual number crunching (ok, little bit crunching), the other does the input. Unfortunately, your input method is also your main method, so you could do that a little better, since main methods are not very good for testing.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // We'll ignore finer problems with scanners, etc. here
playGame(scanner);
}
public static void playGame(Scanner scanner) {
System.out.println("Guess the number of Apples Tom has");
Scanner sc= new Scanner(System.in);
int number=sc.nextInt();
System.out.println("Tom, is it higher or lower?");
String higherOrLower=sc.nextLine();
while(true){
number= getValue(higherOrLower,number);
System.out.println("Tom, is it higher or lower?");
higherOrLower=sc.nextLine();
if(higherOrLower.equalsIgnoreCase("none")) {
break;
}
}
}
This little change will make your code much more testable. Let's start with the easy part, the getValue method:
#Test
public void lower_should_return_number_minus_1() {
int result = getValue("lower", 10);
Assert.assertEquals(9, result); // simple assertions
}
#Test
public void higher_should_return_number_plus_1() {
int result = getValue("higher", 10);
Assert.assertEquals(11, result); // simple assertions
}
#Test
public void garbage_should_return_same_number() {
int result = getValue("Hello, Polly!", 10);
Assert.assertEquals(10, result); // simple assertions
}
This will test most of your possibilities. It would be a good idea to also test what happens if you enter null for a String, just to be sure ;-)
Testing the other method will be a little bit harder, since it involves a little tricking...
#Test(timeout=1000)
public void game_should_work_on_input() {
final ByteArrayInputStream stream = new ByteArrayInputStream(String.format("5%nlower%nlower%nnone%n").getBytes());
final Scanner scanner = new Scanner(stream);
playGame(scanner);
}
Here we simply create a "fake" input, that consists of "5", "lower", "lower" and "none" (honestly, there's a blank line between 5 and the first lower). The String.format will add the correct new line char(s) for each %n. If your test succeeds, it means the game was played to the end. If not, a timeout will happen auf 1000ms (which means your game did not end correctly, which it should). Didn't test it, honestly, but you can go from there, I'm sure. ;-)
Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);