Anyone please help me with the break of the while loop, I just want to end the program when user types nothing in, but why cannot it work? Please do help, thanks a lot.
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class Determining_Pi_Experiment {
public static void main(String[] args) {
while (true) {
System.out.println("Press 'enter' to exit, or type an integer number indicating for how many times you " +
"want the experiment run: ");
Scanner input = new Scanner(System.in);
if(!input.equals(null)) {
if(input.hasNextInt()) {
System.out.println("Processing...");
Random rand = new Random();
int ExperimentTimes = input.nextInt();
double count_success = 0;
double Pi = 0;
for (int i = 0; i < ExperimentTimes; ++i) {
double x = rand.nextDouble();
double y = rand.nextDouble();
double distance = Math.pow(Math.pow((x - 0.5), 2) + Math.pow((y - 0.5), 2), 0.5);
if (distance <= 0.5) {
++count_success;
}
}
Pi = (count_success / ExperimentTimes) * 4;
System.out.println("Pi is approximately equal to: " + Pi);
}
else {
System.out.println("Invalid input.");
}
}
else if(input.equals(null)) {
System.exit(0);
}
}
}
}
I can see many mistakes in your code, I'll walk you through them.
1) Overly complex, overly verbose, checks that aren't needed
2) Missuse of the #equals method
3) Not following standard naming conventions
4) General misunderstanding of how to structure an input-reading loop
To expand on them:
1) Try to simplify your code, remove the while true loop and the else clause (see point 4), declare variables only once, outside, remove reduntant parentheses.
Also, the distance can be computed as Math.hypot(x1-x2, y1-y2) (See here)
2) Notice that the equals method should be used to check if an object is equal to another object. If it were to return true in your example, that would mean that the scanner itself is null (not what it's reading), so the check couldn't work because a NullPointerException would be thrown (calling a method on the null scanner). To check if a Scanner (or any object) is null, you instead want to do anyObject == null. Notice that this has nothing to do with the Scanner input (see point 4).
3) Please correctly name the variables (see here).
4) If you want to keep reading the user input up to the point where no more input is available, you should use Scanner#hasNext . If you instead want to end when an empty string is entered, you should indeed check that the string is empty. This has nothing to do with the scanner being null. someString.isEmpty() will do the job for you.
Pseudo loop:
while(scanner.hasNextLine() && !((line = scanner.nextLine()).isEmpty()))
//do something with the input, stored in the line String
//Exits when enter is pressed (or EOF)
Related
I'm trying to finish a project for one of my courses and I'm almost done, but having issues. For this I was able to get something to work but I'm not really sure how I should go about breaking it into the required classes.
The final project is supposed to have a GuessApp class that runs the simple guessing game using the GuessLogic (which I have as correct) which handles the logic of the game. In other words, the GuessApp class is not to keep track of the correct answer, the number of guesses made, the numbers previously guessed, or whether a guess is legal. On the other hand, the GuessApp class is responsible for all of the I/O. In other words, the GuessLogic class is not to print anything (except possibly for the purposes of debugging).
So my question is essentially how do I break up my code into these 2 classes and we were also supposed to implement a toString method in your GuessLogic class that returns the state of the GuessLogic object (that is, all of its member variables) as a single string. How would I do this?
My code thus far:
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
int guess;
int NumGuess = 1;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
if (hs.contains(guess)) {
System.out.println("You have already entered this number");
continue; // this will repeat the loop
}
if (guess < 0 || guess > 10) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue; // this will repeat the loop
}
System.out.println("Your guess is " + guess);
if (guess == GuessLogic) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
return; // this will stop the loop
}
else if (guess < GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
NumGuess++;
}
else if (guess > GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
NumGuess++;
}
hs.add(guess);
} while (true);
}
}
Well, do it by steps.
Create the GuessLogic class, and move to it all the data fields.
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
int guess;
int NumGuess = 1;
...
Provide a method to add a guess
public void guess(int guess){
this.guess=guess;
this.NumGuess++;
validate();
}
Implement the validate method. Here you have loads of choices. You could keep an enumeration with the current state, something like
enum State {
START,
DUPLICATE,
OUT_OF_RANGE,
LOWER,
HIGHER,
MATCH
}
And validate would set the state.
Then your App queries the state and print the actual message.
Or, which would be simpler, your logic should calculate the message and just maintain a boolean shouldStop, that the app would query to know if it should prompt again or exit
the toString() method, you could just concatenate all the field values (most objects in the Java API have a meaingful toString(). Hint: a good IDE can generate the toString() automatically from the fields.
Hope this helps, and don't be afraid to try things!!
I'm relatively new to Java and I'm trying to write a program for my computer programming class that will accept a string from the user (the string must be something like 1 + 2 - 1) and then take the string, use a delimiter to get rid of the +/- signs, and then perform the addition and subtraction and return the sum of the string input. To do this, my program has to run through a while loop and each time an integer is found it must perform the appropriate function based on whether a + or - sign preceded the number. I'm trying to use .findInLine to have the program determine whether the character is a + or - and then based on this add or subtract the number that follows, but it doesn't seem to work while also using a delimiter and I'm stuck as to what to do. Here's my code:
import java.util.*;
import java.io.*;
public class Lesson17p1_ThuotteEmily
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.println("Enter something like 8 + 33 + 1,257 + 137");
String s=kb.nextLine();
Scanner sc=new Scanner(s);
char c=sc.findInLine("\\+").charAt(0);
sc.useDelimiter("\\s*\\+\\s*");
double sum=0;
while(sc.hasNextInt());
{
if(c=='+')
{
sum=sum+sc.nextInt();
System.out.println(sum);
}
}
System.out.println("Sum is: "+sum);
}
}
I had code for - signs in the program previously but deleted them temporarily because I want to figure out how to make the program run for addition problems and then I'm going to add in the subtraction programming later, using the same thing that worked for addition.
My code compiles and runs fine, but when it gets to the part where it should be adding and then returning the sum of the problem, it stops. It doesn't return an error or anything, it just freezes. I'm not really sure why this is happening. I need the delimiter for the loop and addition to work, and when I tried taking that out it returned an error. I could remove the find in line but then I'll need a different way for the program to determine whether to add or subtract and I'm struggling to think of anything. I've also tried rearranging my code so it will find the + or - sign first, then use a delimiter to get rid of the symbol and proceed with the addition or subtraction, but again the program froze.
Any help you can give is much appreciated!
Remade the code with comments:
import java.util.Scanner;
import java.util.LinkedList;
public class AddSubstract {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.print("Type in an expression using + and - operators.\n>> ");
String userInput = userInputScanner.nextLine();
// our example input: " 35 - 245 + 34982 "
userInput = userInput.trim();
// input is now "35 - 245 + 34982"
if(userInput.charAt(0) != '-') userInput = "+" + userInput;
// we need to change the input to a set of operator-number pairs
// input is now "+35 - 245 + 34982"
int result = 0;
// result
byte sign = 0;
// sign; 1 -> positive number, -1 -> negative number, 0 -> not yet checked
int numberToPush = 0;
for(char c : userInput.toCharArray()) {
if(c == '+' || c == '-') {
if(sign == 0) sign = (c == '+')?1:-1;
else {
result += sign*numberToPush;
sign = (c == '+')?1:-1;
numberToPush = 0;
}
} else if(c >= '0' && c <= '9') {
numberToPush = ((int) c-'0') + 10*numberToPush;
}
}
result += sign*numberToPush;
System.out.println("The result is: "+result);
}
The following program is supposed to calculate the square of a number (Different program from previous question) I tried doing this because the previous program used bufferedReader with this in attempt to use scanner. For instance when entering 2 as the number it outputs 1.0 as the squared value of that number. Any help would be much appreciated! Btw sorry for the spacing i can't get past the first screen unless I space each line 4 times for some reason.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner in=new Scanner(System.in);
System.out.println("the sqare of that number is "+sqrt(in.nextInt()));
}
static double sqrt(double x){
double result;
double i=0;
if(x<0)
result=-1;
else{
while (true){
if((i*i)>x)
break;
i++;
}
i=i-1;
result= (i * i);
result= (i * i);
}
return result;
}
}
Why are you returning result? The i variable holds the square-root at the end of the while-loop, try returning i. Then, that first if-statement can simply become:
if (x < 0)
return -1;
and you can get rid of result completely.
I do not fully understand what your goal is here. Your while-loop calculates the square-root of x - what's the point of that? Why not just return x*x? In fact, you don't even need the (rather poorly named) sqrt method:
System.out.print("Enter a number: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("The sqare of that number is " + (n*n));
in.close();
It looks like what you want in you while loop is if ( i > x) break;. Then the result should be correct because you subtract 1 from i after the while loop - making it equal to x. So, result = i * i is the square of x since i == x.
I need help understanding how to write a for loop that takes in a certain amount of integers (must be 1 through 10) and it stops taking in numbers once 0 is entered (0 will be the last number). My code so far is:
import java.util.Scanner;
public class countNum {
public static void main(String[] args) {
int[] array;
Scanner input = new Scanner(System.in);
System.out.println ("Enter in numbers (1-10) enter 0 when finished:");
int x = input.nextInt();
while (x != 0) {
if (x > 2 && x < 10) {
//Don't know what to put here to make array[] take in the values
}
else
//Can I just put break? How do I get it to go back to the top of the while loop?
}
}
}
}
I don't understand how to simultaneously initialize an array with a set length while having the Scanner read a certain amount of digits of that unknown length, until 0 is entered, and then the loop stops taking in input for the array.
Thanks for any help!
Ok here's the bit more detail: -
You need to use an ArrayList if you want a dynamically increasing array. You do it like this: -
List<Integer> numbers = new ArrayList<Integer>();
Now, in your above code, you can put your number reading statement (nextInt) inside the while loop, since you want to read it regularly. And put a condition in while loop to check whether the entered number is an int or not: -
int num = 0;
while (scanner.hasNextInt()) {
num = scanner.nextInt();
}
Further, you can move on your own. Just check whether the number is 0 or not. If it is not 0, then add it to ArrayList: -
numbers.add(num);
If its 0, break out of your while loop.
And you don't need that x != 0 condition in your while loop, as you are already checking it inside the loop.
In your case, the user seems to be able to input any number of digits. For this scenario, having an array is not ideal simply because the size of the array needs to be known prior to the array initialization. You have some options though:
Use an ArrayList. This a dynamic data structure which expands dynamically.
Ask the user the amount of numbers he/she is going to be entering and use that to initialize the array.
Create an array basing yourself on some assumption on the size.
In both cases 2 and 3, you would also need to include some logic that will make the program stop when: (1) The user enters 0 (2) OR when the amount of numbers provided by the user exceeds the size of the array.
I would recommend sticking to the first solution though since it is easier to implement.
I strongly recommend you go get some hands on with Java Collections.
you can fix your program as
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class arrayQuestion {
public static void main(String[] args) {
List<Integer> userInputArray = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 Numbers ");
int count = 0;
int x;
try {
do {
x = input.nextInt();
if (x != 0) {
System.out.println("Given Number is " + x);
userInputArray.add(x);
} else {
System.out
.println("Program will stop Getting input from USER");
break;
}
count++;
} while (x != 0 && count < 10);
System.out.println("Numbers from USER : " + userInputArray);
} catch (InputMismatchException iex) {
System.out.println("Sorry You have entered a invalid input");
} catch (Exception e) {
System.out.println("Something went wrong :-( ");
}
// Perform Anything you want to do from this Array List
}
}
I hope this will solve your doubt..
beyond this u need to handle Exceptions if user enters any character or invalid inputs as above
I'm writing a java program that will count up to a number that the user inputs. The user is only allowed to input a number that is between 1-10.
For instance:
if the user entered 6 the output will be:
1 2 3 4 5 6
How do I do this with only using operators and while and if statements?
Here's my code. I've been painfully trying to figure out why my code won't work. Thanks in advance!
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
System.out.println("Hi user, input any number that is between 1-10");{
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 0;
if (1<=num1 && num1>=10);
num2=0;
while (num2 < num1)
System.out.println(""+(num2 + 1));
num2++;
}
}
}
I think the problems lies with the code-blocks (the stuff between {}). Especially look at how the while-loop behaves. What is supposed to be in the loop and what not? Also, your if-statement is empty. The ; closes the code-block that is handled by the if.
An IDE can help you detect these errors by applying syntax-formatting. The comments in your code looked like they were coming from Eclipse. Try ctrl-shift-f (or look it up in the menu). This automatically formats and indents your code, this makes it easier to detect errors in the structure.
The if has a stray trailing ; As a result, the next line is always run.
I make it a point to include even single line statements involved with conditional statements and loops inside {/}. That helps make the start & end of the code block clear. My earlier comment about the code indentation is also a factor in identifying where code block begin & end.
First, your conditional check should use an or and braces; and assign 0 to num1, as to prevent the loop from running if the user inputs anything outside the 1-10 range:
if (num1 < 1 || num1 > 10){
num1=0;
}
And you can also improve your loop:
while (num2 < num1) {
System.out.println( ""+ num2++ );
}
Also, as said by user689893, check your {} blocks.
in while loop just change
while (num2 < num1){
if(num2==0)
System.out.println((num2 + 1));
else{
num2++;
System.out.println(num2);
}
}
Try this one
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi user, input any number that is between 1-10");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 1;
if (1<=num1 && num1>=10){
num2=1;
while (num2 <= num1)
{
System.out.println("" + num2);
num2++;
}
}
}
}