I am learning java, using the book "Java how to program". I am solving exercises. In this actual exercise I am supposed to make a program which reads an integer from the user. The program should then display a square of asterisks (*) corresponding to the integer read from the user. F.eks user inputs the integer 3, the program should then display:
***
***
***
I try to nest a while-statement inside another, the first one to repeat the asterisks on one line, the other one to repeat this the right amount of times. Unfortunately, I only get the program to display one line. Could anyone tell me what I am doing wrong please?
The code is as follows:
import java.util.Scanner;
public class Oppgave618
{
public static void main(String[] args)
{
int numberOfSquares;
Scanner input = new Scanner(System.in);
System.out.print("Type number of asterixes to make the square: ");
numberOfSquares = input.nextInt();
int count1 = 1;
int count2 = 1;
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count2++;
}
}
}
You should reset count1 back in each iteration of the outer loop
public static void main(String[] args) {
int numberOfSquares;
Scanner input = new Scanner(System.in);
System.out.print("Type number of asterixes to make the square: ");
numberOfSquares = input.nextInt();
//omitted declaration of count1 here
int count2 = 1;
while (count2 <= numberOfSquares) {
int count1 = 1; //declaring and resetting count1 here
while (count1 <= numberOfSquares) {
System.out.print("*");
count1++;
}
System.out.println();
count2++;
}
}
count1 needs to be reset every time you move to the next line, e.g.
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count1 = 1; //set count1 back to 1
count2++;
}
Unless the exercise requires while-loops, you really should use for-loops. They will actually prevent such bugs from occurring, and require less code. Also, it is idiomatic in most programming languages to start counting from zero and use < rather than <= to terminate the loop:
for (int count2 = 0; count2 < numberOfSquares; ++count2)
{
for (int count1 = 0; count1 < numberOfSquares; ++count1)
System.out.print("*");
System.out.println();
}
Related
So in this code I had created a code to read 6 values and print the highest of the 6 numbers. That worked well but now if one of the numbers are negative, I want the loop to stop there and exit printing Invalid Loop. But in my code the program prints the highest mark after printing Invalid Input. How do I avoid this?
This is on IntelliJ platform Java v5.0
import java.util.Scanner;
class Highestmark {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a[] = new int[6];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt(); // To exit loop
if (a[i] < 0) {
System.out.println("Invalid Mark");
break;
}
}
int max = a[0];
for (int i = 0; i < a.length; i++) { // To find highest
if (max < a[i]) {
max = a[i];
}
System.out.println("Highest Mark is" + max);
}
}
}
I expect the output to be
25
-26
Invalid Input
But the actual output is
25
26
27
-28
Invalid Input
Highest Mark is 27
This can be simplified a bit, no need to keep an array:
public class HighestMark {
private static final int MAX_INPUT = 6; // could just hard-code this in loop, but good practice to set constants
private static final Scanner SCAN = new Scanner(System.in);
public static void main(String[] args) {
int highest = 0;
for (int i = 0; i < MAX_INPUT; i++) {
int next = SCAN.nextInt();
if (next < 0) { // validate the input (require non-negative int)
System.out.println("appropriate error message...");
break;
}
if (next > highest) {
highest = next;
}
}
System.out.println("Highest mark is " + highest);
}
}
The break only breaks the for-loop but then continues with the code below. You probably just say return instead or System.exit(0);
You need a boolean flag.
Set the flag to false, when there is any negative number.
Check the flag before checking max number.
Scanner sc = new Scanner(System.in);
int a[] = new int[6];
boolean flag = true;
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt(); // To exit loop
if (a[i] < 0) {
System.out.println("Invalid Mark");
flag = false;
break;//return; //System.exit(0); any of these 3 will work fine.
}
}
if (flag) {
int max = a[0];
for (int i = 1; i < a.length; i++) // To find highest
{
if (max < a[i])
max = a[i];
}
System.out.println("Highest Mark is" + max);
}
I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}
I need to write a program that asks for 20 numbers and outputs the amount of even numbers. I figured out the loop part (for-loop) but i don't have any idea how to collect the data if that makes any sense.
Here is the loop:
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
num = input.nextInt();
}
If you want to give the numbers when you run the program you can use this:
public static void main(String[] args) {
int counter=0;
Scanner sc = new Scanner(System.in);
System.out.println("Write 20 numbers:");
for(int i=0; i<20; i++) {
System.out.print("Number " + i + ":");
int temp =sc.nextInt(); //this waits for you to write an int
if(temp%2==0)
counter++;
}
sc.close();
System.out.println("Even numbers:" + counter);
}
i've tested it ant it works, keep in mind that you need to press enter after you write each number
You can use the code like this:
int count = 0;
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
if (input.nextInt() % 2 == 0)
count++;
}
You can use the modulo operator to check if a number is divisible by another number (in this case - by 2). Note, BTW, that your code overwrites the loop variable, which is probably not what you meant:
int evens = 0;
for (int i = 0; i < 20; i++) {
num = input.nextInt();
if (num % 2 == 0)
evens++;
}
}
System.out.prinf("You inputted %d even numbers%n", evens);
Do you mean some thing like this ?
Scanner input = new Scanner(System.in);
int inputs[] = new int[20];
System.out.printf("Please enter %d numbers\n",inputs.length);
for(int i = 0; i < inputs.length;i++){
System.out.println("Enter value number "+(i+1));
int value = input.nextInt();
inputs[i]=value;
}
Print an arrowhead.
Let the user input how big the arrow should be by entering the total number of lines to draw.
The user entered 9 in the example below. Prompt the user to enter an odd number only.
It should model this:
*
**
***
****
*****
****
***
**
*
So far my code looks like this:
int i, j, numRows;
Scanner reader=new Scanner(System.in);
System.out.println("How many rows would you like the triangle to have?");
numRows=reader.nextInt();
//row
for(i=1;i<=numRows;i++){
//column
for(j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
this is the top half. i can make the bottom half by altering the nested loop. I know that I need to have the nested loop decrease the amount of stars after it reaches the middle column, or (i/2)+1, but I am not sure how to do this. I tried using an if statement with j-- inside of the column loop but either that is not correct or I made a mistake.
put this for bottom half:
for(i=numRows;i>=0;i--){
for(j=i-1;j>0;j--){
System.out.print("*");
}
System.out.println();
}
You can use two nested loops similar to what you have now. Think about what starting value the inner loop should use and what the condition of the loop should be.
int i, j, numRows;
int modifier=1;
Scanner reader=new Scanner(System.in);
System.out.println("How many rows would you like the triangle to have?");
numRows=reader.nextInt();
//row
for(i=1;i>0;){
//column
for(j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
if (i == numRows) {
modifier=-1;
}
i=i+modifier;
}
I really shouldn't be doing your homework... but i always get sucked into these questions cuz they're trivial and sorta fun for me to solve...
My professors would always think I was strange because I never answered the problem the most straight-forward manner. :)
public static void printStarArrow() {
int i = 0;
int j = 0;
int numRows = 0;
Scanner reader = new Scanner(System.in);
System.out
.println("How many rows would you like the triangle to have?");
numRows = reader.nextInt();
if (numRows <= 0 || numRows % 2 != 1) {
System.out.println("Please enter an odd number only.");
return;
}
// row
for (i = 1; i <= numRows; i++) {
if (i <= (numRows / 2) + 1)
j = i;
else
j = --j;
printStar(j);
}
}
public static void printStar(int size) {
for (int i = 0; i < size; i++) {
System.out.print("*");
}
System.out.println("");
}
This is my code
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
int tri, a;
int b;
System.out.println("Enter the size you want your triangle to be:");
tri = keyboard.nextInt();
for (a = 1; a <= tri; a++)
{
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
}
}
When i run and enter ex. 3 i want the code to say
I know i might be missing some loops as I am in the beginning stages of the code only. I am running to see if everything goes as i want and it isn't. When i enter 3 i get everything on one line:
******
Help with explanation would be appreciated.
It should work with any number not just 3
You need to make two changes to your code. First, you need to end the line on each iteration of the outer loop. Second, you need to do the bottom part of the triangle. Here's code that does it both:
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
int tri, a;
int b;
System.out.println("Enter the size you want your triangle to be:");
tri = keyboard.nextInt();
for (a = 1; a <= tri; a++)
{
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
// this next call ends the current line
System.out.println();
}
// now for the bottom of the triangle:
for (a = tri - 1; a >= 1; a--) {
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
System.out.println();
}
}
Or just one loop:
int x = 3; // input tri
var y = x*2;
for (int i = 0; i < y; ++i) {
for (int j = 0; j < (i < x ? i : y-i); ++j) {
System.out.print("*");
}
System.out.println();
}
System.out.print prints everything in the current output buffer i.e. the console. You must use System.out.println (note the ln suffix) to print something and a break line.
This needs to be done every time the outer loop is accessed:
system.out.println();
this allows the *'s to be on different lines, also this code only does the top half of the triangle. In order to do the bottom half, you have to count down from tri.