Java program stalls then stops when it reaches a loop - java

I have a program (written in Java) that when it reaches a for or a while loop, it stalls for about 2 seconds then stops completely. Here is the code:
import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct=false)
for(x=0;x>999999999;x++)
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}
You can see that I have comments for the while loop stuff. Also, I have put in 4 println statements where I thought it would be getting stuck, and it printed 1 and 2, but not 3. Here is the portion of my cleanUsage class that contains the random number generator:
public static int random(int min, int max)
{
int range = max - min + 1;
int number = (int) (range * Math.random() + min);
return number;
}
I have asked some other people and they could not figure it out. If you could help me out, that would be great.

It doesn't print 3 or 4 because the condition x>999999999 is initially false so that for loop is never entered. I assume you meant <.
Also note that you can use break rather than correct = true to exit a loop.

import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct==false) // equality test, not assignment
for(x=0;x<999999999;x++) //2nd argument is continue while false
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}

Related

declaring int input = Integer.parseint(scanner.nextLine()) vs Integer.parseint(scanner.nextLine())?

so I am working through MOOCfi and I am on the statistics problem. It's straightforward, just input numbers and return the sum of it until user enters -1. Here are the two classes:
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Statistics statistics = new Statistics();
while(true) {
int input = Integer.parseInt(scanner.nextLine());
if (input == -1) {
System.out.println("Count: " + statistics.getCount());
System.out.println("Sum: " + statistics.sum());
System.out.println("Average: " + statistics.average());
break;
}
statistics.addNumber(input);
}
}
}
Statistics.java
public class Statistics {
private int count;
private int sum;
public Statistics() {
this.count = 0;
}
public void addNumber(int number) {
this.count += 1;
this.sum += number;
}
public int getCount() {
return this.count;
}
public int sum() {
return this.sum;
}
public double average() {
return (1.0)*(this.sum/this.count);
}
}
My question is, for the line int input = Integer.parseInt(scanner.nextLine()). I wrote earlier:
if (Integer.parseInt(scanner.nextLine())
AND then
statistics.addNumber(Integer.parseInt(scanner.nextLine())
a few lines down, it whenever I ran it, it gave me some buggy inputs. Sometimes I would have to input -1 twice in order for it to stop, and by that point, the results were wrong. Specifically, entering 5,2,2 gave me a
Count: 2
Sum: 1
Average: 0.0
when it should be
Count: 3
Sum: 9
Average: 3.0
It seems like the if statement ALSO needs the int input rather than the Integer.parseInt(scanner.nextLine()) because putting that in there while keeping statistics.addNumber(input) yields a completely different answer if they were flipped. Is this some sort of weird java thing where assigning Integer.parseInt(scanner.nextLine()) to a int is different than just using it straight up?
Thank you!

How to call method from 1st method to 2nd method in a class

The number is given and we need to find if it is a square number or triangle number?
This "num" should 1st verify the square method then it has to go for triangle method.
there issue is: how can i call from square to triangle or any other methed to call the Triangle method if my square method won't suit.
Here's my code:
public class HelloWorld{
public static void main(String []args){
class Number{
int num;
public boolean isSquare(){
int squareNumber=1;
while(squareNumber<num){
squareNumber = num*num;
}
if(squareNumber%num==0)
{
System.out.println(num+" is a Square number");
}
else
{
return isTriangle();
}
boolean isTriangle() {
int x=1,triangleNumber=1;
while(triangleNumber<num){
x++;
triangleNumber = triangleNumber + x;
}
if(triangleNumber==num)
{
System.out.println(num+" is a triangle number");
}
else
{
System.out.println(num+" is applicable for both triangle and square numbers");
}
}
}
}
Number mynum = new Number();
mynum.num=2;
System.out.println(mynum.isSquare());
}
}
So first it would be much easier for you to just do this:
public boolean isSquare(int num){
...
}
And so get rid of:
mynum.num = yourNumber;
As very often you will encounter this approach in methods, where the raw input is can be any number/text...
Now for your code, a very good optimization is:
public boolean isSquare(int num){
if (num>0) //To check if the number is null or not...
squareNumber = num*num;
}
Because the while loop condition is always met once and then exited after the first entry...
Moving on to the next part... which for me, is very tricky as I see it useless because it always returns true (the text) as the "squareNumber" always has num as root, and will always pass if (squareNumber%num==0) as true, and isTriangle(...) will never be called.
The more approachable way is:
public class HelloWorld {
static String result;
public static void main(String[] args) {
int mynum = 36;
System.out.print(isSquare(mynum)+isTriangle(mynum));
}
public static String isSquare(int num){
if ((Math.sqrt(num)==(int)Math.sqrt(num))){
return "Given number is a square";
} else return "Given number isn't a square,";
}
public static String isTriangle(int num){
if (isSquare(8*num+1)){
return " but is still a triangular number!";
} else return " but not a triangular number.";
}
}
public static void main(String []args){
class Number{
int num;
public boolean isSquare(){
int squareNumber=1;
while(squareNumber<num){
squareNumber = num*num;
}
if(squareNumber%num==0)
{
System.out.println(num+" is a Square number");
}
return isTriangle();
}
boolean isTriangle() {
int x=1,triangleNumber=1;
while(triangleNumber<num){
x++;
triangleNumber = triangleNumber + x;
}
if(triangleNumber==num)
{
System.out.println(num+" is a triangle number");
return true;
}
else
{
System.out.println(num+" is applicable for both triangle and square numbers");
}
return false;
}
}
Number mynum = new Number();
mynum.num=2;
System.out.println(mynum.isSquare());
}

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

What are the errors here?

import java.util.Scanner;
public class program4
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled;
System.out.println("Your result is" + doubleNumber(number));
System.out.println(" thank you for using my program ");
}
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
if (integerDoubled < 100 ); {
less_100(integerDoubled);
} else if ;
greater_100(integerDoubled);
public static int less_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*2);
}
public static int greater_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*3);
}
}
}
I think the error is in the If statement but i don't know how to fix it.
I know integerDoubled is a local variable and i should make it global but I'm not sure how to do that. should i put the if statement together with the doubleNumber function??
If you formatted your code (your IDE will do this for you), you would see that the if statement is not inside a method as it must be. If you use your IDE correctly, finding and correcting such error would be much faster and you barely have to think about it.
I tried to make sense of your program this is what I came up with
import java.util.Scanner;
public class T
{
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled=doubleNumber(number);
System.out.println("Your result is" + integerDoubled);
System.out.println(" thank you for using my program ");
if (integerDoubled < 100 ) {
less_100(integerDoubled);
}
else
greater_100(integerDoubled);
}
public static int less_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*2);
}
public static int greater_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*3);
}
}

How to take integers being printed by a method?

I am making a very simple blackjack game with one class and at least 2 methods. I want to take the random generated numbers that are being output (cards being dealt) and add them so I can make an if else statement to check if the total is over 21 causing the player to lose.
import java.util.*;
public class BlackJack {
private Scanner scan;
static Random generator = new Random();
public BlackJack(){
scan = new Scanner (System.in);
}
public static void main(String[] args) {
StarterCards();
Hit();
}
public static void Hit() {
System.out.println("Hit? (y or n)");
String yes = new String ("y");
Scanner input = new Scanner(System.in);
String yesorno = input.nextLine();
if(yesorno.equals(yes)) {
RandomCard();
Hit();
if()
} else {
System.out.println("Game Over");
}
}
public static void RandomCard() {
int card = generator.nextInt(10) + 1;
System.out.println("Card : "+ card);
int total2 = card;
}
public static void StarterCards() {
int card1 = generator.nextInt(10) + 1;
int card2 = generator.nextInt(10) + 1;
System.out.println("Card : "+ card1);
System.out.println("Card : "+ card2);
}
}
Re:
How to take integers being printed by a method?
The solution: don't have the method print anything. Instead have the method return the number, and let the calling code print it or do with the number whatever it wants to do.
i.e.,
public int myMethod() {
int someNumber = ....; // calculate it here
// System.out.println(someNumber); // don't print it here!
return someNumber
}

Categories