Show lines in java with loops - java

i have a problem with a little java program.
I have to type a number between 1 and 10. This number represents the number of lines. For example: If you type 4, the following image is displayed.
o
oo
ooo
oooo
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int number, count;
System.out.println("Write the number from 1 to 10");
Scanner teklatua = new Scanner(System.in);
String datu = teklatua.nextLine();
number = Integer.parseInt(datu);
if(number> 10 || number< 1)
{
System.out.println(number + " not between 1 and 10, choose again");
}
else
{
for (count=1; count<=number ; count++)
{
System.out.println("o");
for (count=1; count<=number; count++)
{
System.out.print("o");
}
}
}
}
}
Thanks!!
Edit:
Sorry, my problem was that the execution of the code gives me:
o
oooo
and I did not know how to solve it

I haven't seen the question. But I assume the problem is using of "count" variable as an iteration variable in two loops. To fix it just use another variable like:
public static void main(String args[])
{
Scanner teklatua = new Scanner(System.in);
int number = -1;
while (number> 10 || number< 1)
{
System.out.println("Choose a number between 1 and 10");
String datu = teklatua.nextLine();
number = Integer.parseInt(datu);
}
for (int i=0;i<number;i++)
{
for (int a =0;a<i+1;a++)
System.out.print("o");
System.out.println();
}
}

Consider using a helper method for the validation of the user's input:
import java.util.Scanner;
class Main {
private static int getIntegerInput(Scanner scanner, String prompt, int minValue, int maxValue) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
if (validInteger >= minValue && validInteger <= maxValue) {
break;
} else {
System.out.printf(
"Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
}
} else {
System.out.printf(
"Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minLines = 1, maxLines = 10;
String numLinesPrompt = "Please enter the number of lines: ";
int numLines = getIntegerInput(scanner, numLinesPrompt, minLines, maxLines);
for (int i = 0; i < numLines; i++) {
for (int j = 0; j <= i; j++) {
System.out.print('o');
}
System.out.println();
}
}
}
Example Usage:
Please enter the number of lines: 12
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: -2
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: a
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: 5
o
oo
ooo
oooo
ooooo

You might want add another variable for the inner loop. Somthing like this:
....
for (int row = 1; row <= number; ++row) {
System.out.println("o");
for (int column = 1; column <= row; ++column) {
System.out.print("o");
}
}
....

The nested loops need to be updated:
the outer loop has a separate counter of lines i which also defines how many "o" are printed
the inner loop prints not more than i characters
upon ending the inner loop, new line is printed
for (int i = 1; i <= number; i++) {
for (count=1; count <= i; count++) {
System.out.print("o");
}
System.out.println();
}
Another approach could be to use String::repeat instead of inner loop:
for (count = 1; count <= number; count++) {
System.out.println("o".repeat(count));
}

your second forLoop is wrong
it should be something like
for(int j=1;j<=n;j++) {
for(int i=1; i<=j; i++) {
System.out.print("0");
}
System.out.println();
}

Related

How do I make a random int into a variable I can use and compare in Java?

its not great code I know but I need help at line 30 with if (guess == roll) im trying to make it if you guess the number right it will say you win and if not it will not say you win.
import java.util.Random;
import java.util.Scanner;
public class diceGame
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
diceGame test = new diceGame();
System.out.println("Number of rolls?: ");
int numRoll = scan.nextInt();
System.out.println("Gues the number/most common number: ");
int guess = scan.nextInt();
Random rand = new Random();
for(int i = 0; i < roll.length; i++)
{
roll[i] = rand.nextInt(6)+1;
}
for(int i = 0; i < roll.length; i++)
{
System.out.print(roll[i] + ", ");
}
if (guess == roll)
{
System.out.println("Good job you guess correct");
}
else
{
System.out.println("You did not guess correct");
}
}
}
If you would like to guess the number with the highest frequency after n number of rolls, you can update the count of each roll into an array instead of storing the roll outcome of each roll into the array:
for(int i = 0; i < roll.length; i++)
{
roll[rand.nextInt(6)]++; //store count of each roll
}
To find out if you guessed the most frequency roll, find the maximum value (most commonly rolled number) of the array:
int maxIdx = 0;
for(int i = 0; i < roll.length; i++)
{
if(roll[i] > roll[maxIdx])
maxIdx = i;
}
To compare your guess against the most common number:
if (guess == maxIdx+1) //+1 to maxIdx to offset array start index
{
System.out.println("Good job you guess correct");
}
else
{
System.out.println("You did not guess correct");
}

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Why is my code not incrementing?

So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));

odd/even number program doesn't print anything

When I run this nothing prints, I am trying to print a message saying odd or even depending on what the user types.
import java.util.Scanner;
public class Questions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
for (int i = 0; i > 0; i = +2) {
if (number == i) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
}
Your loop is never entered, because you initialize i with 0 and your first test is i > 0 (and you don't want a unary 2, = +2). I would also use formatted IO. Putting that together, I think you wanted something like
int number = input.nextInt();
for (int i = 0; i < number; i++) {
if ((i % 2) == 0) {
System.out.printf("%d even%n", i);
} else {
System.out.printf("%d odd%n", i);
}
}
If you're trying to avoid modulo (and use addition by 2) you could optimize with something like
int number = input.nextInt();
for (int i = 0; i < number; i += 2) {
System.out.printf("%d even%n", i);
System.out.printf("%d odd%n", i + 1);
}
Try this
import java.util.Scanner;
public class Questions {
public static void main (String[]args) {
Scanner input= new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
if(number % 2 == 0)
System.out.println("even");
}else {
System.out.println("odd");
}
}
may be you want to try this way...
if ((number % 2) ==0) {
System.out.println("even");
} else {
System.out.println("odd");
}
As you initialize i and the condition seems to be i>0 so it will always be false so for loop never executed
As #MadProgrammer stated in comments your loop never executed.
because i = 0, the loop is never executed ;)

Java - Using for loops to read user input

In Java, I am having trouble running multiple loops using a single sequence of user-inputted integers. Individually, they run fine individually but together it prints out incorrect numbers.
I'm at a loss as to what is causing this problem.
Here is my code.
import java.util.Scanner;
public class SequenceTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers. " +
"Enter a non-integer to terminate");
int sequence = in.nextInt();
//Print One
int min = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input < smallest)
{
smallest = input;
}
}
System.out.println(smallest);
//Print Two
int max = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input > max)
{
max = input;
}
}
System.out.println(max);
//Print Three
int even = 0;
int odd = 0;
while(in.hasNextInt())
{
int input = in.nextInt();
if((input %2) == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println( even);
System.out.println(odd);
//Print Four
double total = 0;
int count = 0;
while (in.hasNextInt())
{
Int input = in.nextInt();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
System.out.println(average);
}
}
Your code is very fragmented, but it looks like you can achieve what you want with one loop since the loop condition is the same in all of them. This, of course, is only based on the vague description you gave us.
while(in.hasNextInt()) {
int input = in.nextInt();
if(condition1) {
//do stuff
} else if (condition2) {
//do other stuff
} else if (conditionN) {
//do other other stuff
} else {
//last of the stuff to do
}
}

Categories