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++;
}
}
}
}
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 am taking an online MOOC to learn Java, the only problem i have is it is from the university of Helsinki in Finland i live in the US so there are limited times when i can be awake to ask for help on an exercise. my current exercise is to ask the user for a number and then print each whole number up to that number while using a
while {
}
statement
this is the code i have currently
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
System.out.print("up to what number?:"+ number);
while (number<=number){
System.out.println(number);
number++;
}
}
and what it looks like it is doing is ignoring the
while (number<=number) {
System.out.println(number);
part of my code and proceeding straight to the
number++;
portion of my code do i need to declare another int(variable) to store a value?
the way the course has the test cases for grading i can't simply declare a variable with a definite value as they run several test cases like positive numbers and negative numbers.
is there a way to use the reader to store a value to two separate variables so that they can be compared against each other and only print the numbers up to that number?
i also know that i am missing a
Break;
statement but i am not sure where i would place it in the code i have, i have tried to use
} else {
break;
but get an error stating that i have an else without an if.
i am using netbeans as it is required for my course because the server submissions are setup through TMC.
thinking about it now i'm sure its not skipping the while statement but simply continues to print because as it prints and increments the users input is incremented as well since i only have the one variable but i am again not sure how i would go about storing the user input value in two different variables where i can compare them with the less than or equal to statement and stop the printing once it reaches the number input by the user, in that case i would not necessarily need the break statement as it would stop once it prints up to the number input.
ANSWERED: here is what i finally came up with as my answer.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
while (numbers <= number){
System.out.println(numbers);
numbers++;
}
}
You are comparing number to itself. So (number <= number) is always true.
Use a different variable, such as count to actually count up. Initialize it at zero.
Change the condition to (count < number), then in the loop change the increment to count++ and then output count.
Oh, and you should probably prompt for the number before you read it in.
ie your whole program will be:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int number = Integer.parseInt(reader.nextLine());
int count = 0;
System.out.println(number);
while (count<number){
count++;
System.out.println(count);
}
}
You need another variable to increment upto inserted number
int i=1;
while (i<=number){
System.out.println(i++);
}
What your loop is doing
while (number<=number){
System.out.println(number);
number++;
}
for example number=10 so it's checking like this 10<=10 do you need this,absolutely not.
So for your code you need an another variable to increment up to entered number.
This would do it:
public static void main(String[] args) {
int startingInt = 1; //begin printing from 1
System.out.println("Up to what number?");
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
while (startingInt <=number){
System.out.println(startingInt);
startingInt++;
}
}
i'm c# expert, so first of all please use c#.
But I know I know you can't always select your laguagued, ;)
Here is solution , it works on my machine.
while (number<=number){
System.out.println(number);
number++;
if (number==arg[0]) break;
}
Enjoy the solution!
System.out.println("Up to what number?");
int number = Integer.parseInt(reader.nextLine());
int n = 1;
while (n <= number) {
System.out.println(n);
n++;
}
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);
}
So what this program does is take two numbers as input using the Scanner class, and calculates the lowest common multiple of those two numbers. Everything seems to be working, except the lcm method won't return anything. I may have messed something up with my 'break' statements, but I didn't know any other way to get out of the if statement that is nested in a while loop. One more question: Is using a while(True) loop good practice or bad practice? Because I've seen lots of mixed opinions on it. If anyone has any better alternatives to while(True) loops I'd be happy to hear them. Thank you!
// LCM Calculator
// Author: Ethan Houston
// Language: Java
// Date: 2013-12-27
import java.io.*;
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("This is a LCM calculator\n");
System.out.println("Enter your first number: ");
int firstNumber = scanner.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = scanner.nextInt();
lcm(firstNumber, secondNumber);
}
public static int lcm(int one, int two) {
int counter = Math.min(one, two);
int initialCounter = counter;
boolean running = true;
while (running) {
if (counter % one == 0 && counter % two == 0) {
break;
} else {
counter += initialCounter;
}
}
return counter;
}
}
You do return something, you're just not printing it. Just try:
System.out.println(lcm(firstNumber, secondNumber));
You are not printing the returned value
System.out.println(lcm(firstNumber, secondNumber));
As you had written,
lcm(firstnumber, secondnumber);
this method will return an int type value, but in your code, you are not obtaining the returned value in any variable.
So, you should write like this :
int variable=lcm(firstnumber, secondnumber);
Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable