I am getting unexpected output from this code: - java

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int i = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
while(i<y){
for ( i = 1; i <=y; i=i+x) {
for ( int j = i; j <=(i+(x-1)); j++) {
if(x%2==0 && y%3==0)
{
System.out.print((j-1)+" ");
}
else
System.out.print(j+" ");
}
System.out.println();
}
}
Sample input:
3 99
This is the output I am supposed to get :
1 2 3
4 5 6
7 8 9
10 11 12
...
97 98 99
But when I give my input as
4 99
The output I get is :
0 1 2 3
4 5 6 7
....
96 97 98 99
I am not supposed to start with 0.
What is wrong in my code?

I tried to rewrite your code a little so that it isn't so messy. Is this what you want to achieve?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=input.nextInt();
int y=input.nextInt();
for (int i = 1; i < y + 1; i++) {
System.out.print(i + " ");
if (i % x == 0){
System.out.println();
}
}
input.close();
}

Scanner input=new Scanner(System.in);
int i = 1;
int j = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
for( i = 1; i <=y; i++) {
System.out.print(i);
System.out.print(" ");
j++;
if(j == x){
System.out.println();
j = 0;
}
}
you can use this code to output as you expect.

Your first output is going to be a 4 because at that time x = 3 and y = 99. Neither are even so your else block will be hit. Change if(x%2==0 && y%3==0) to if(x%2==0 || y%3==0) and you will get 0 for the first output. That won't totally fix your problem but it will get you on the right path.

You begin j=1 (because i = 1 the first time you enter the loop)
and if x%2 == 0 (which is the case) you print j-1
of course you will begin with 0, I don't see why you're surprised.
if you want to avoid that, just print :
(j-1)==0 ? "" : j-1 + " "

Related

Limit number of input lines in Java?

I have a problem where I want to take input from the user, the user can insert 1 and up to 8 lines, and each line represents a case.
What I want is to stop the scanner when the user inserts 8 lines, Or if the user wants less than 8 he can press enter or a specific key to end the loop.
What I have done so far:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
The input should be two numbers in each line, one for i and one for j.
Input:
0 0
100 300
99 399
0 200
Output should be:
C1: 0
C2: 100
C3: 1
C4: 200
Hope this explains my problem.
Thanks in advance!
As #Abhishek suggested, you can use a counter variable:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}

How do I print a set of numbers and the sum of the squares from 1 to each number from the list?

How do I code this question in two different methods? I know this can be done within a loop and a nested loop but it needs to be done this way. I'm aware it's all wrong, but I need help understanding the logic.
public static int numloop(int n){
int nd = 0;
for(n = 5; n <= 49; n += 2){
nd = ndiv(n);
}
return nd;
}
public static int ndiv(int numb){
int sumsq = 0;
for( int x = 1; x <= numb; x++ ){
sumsq += x * x;
}
return sumsq;
}
public static void main(String[]args){
System.out.println("NUMBER\t" + "SUMSQ");
System.out.println(n + nd);
}
The output should look like something like this:
Number || Sum of square
5 || 55
7 || 140
9 || 285
It is pretty simple #Tony. If you want this to be done using 2 methods, then just split it up as follows:
One method to just take the input number as parameter and calculate
sum of squares(squares found in another method)
Another method to calculate the squares of the numbers.
So here is the overview of the flow of the program:
Accept the number
pass the number into the 1st method mentioned above
In the 1st method, loop from 1 to the number.. call the Square() method for each i value. calculate the sum simultaneously;
Print the sum once all iterations are done..
I have attached the code and its output below:
CODE:
import java.io.*;
class Main {
public static void main(String[] args)throws IOException {
InputStreamReader ip = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int c = 1;
do {
System.out.println("Enter a number: ");
int n = Integer.parseInt(br.readLine());
squaresum(n);
System.out.println("\nPress 1 to continue, 0 to stop..");
c = Integer.parseInt(br.readLine());
}while(c == 1);
System.out.println("Stopped.");
}
public static void squaresum(int num) {
int n = 0;
for(int i = 1; i <= num; i++)
n += square(i);
System.out.println("Sum is: " + n);
}
public static int square(int n) {
return (n*n);
}
}
OUTPUT:
Enter a number:
5
Sum is: 55
Press 1 to continue, 0 to stop..
1
Enter a number:
9
Sum is: 285
Press 1 to continue, 0 to stop..
0
Stopped.
Tony - could not work out exactly for the code exactly you wanted so I took the liberty of making it a little more flexible. It should be easy for you to restrict it to do only what you want.
public class SumSquare {
public static int numloop(int start, int end, int increment){
int nd = 0;
for(int i = start; i <= end; i += increment){
nd = ndiv(i);
System.out.println(i + " || " + nd);
}
return nd;
}
public static int ndiv(int numb){
int sumsq = 0;
for( int x = 1; x <= numb; x++ ){
sumsq += x * x;
}
return sumsq;
}
public static void main(String[]args){
System.out.println("Number" + " || " + "Sum of square");
numloop(5, 49, 2);
}
}
OUTPUT:
run:
Number || Sum of square
5 || 55
7 || 140
9 || 285
11 || 506
13 || 819
15 || 1240
17 || 1785
19 || 2470
21 || 3311
23 || 4324
25 || 5525
27 || 6930
29 || 8555
31 || 10416
33 || 12529
35 || 14910
37 || 17575
39 || 20540
41 || 23821
43 || 27434
45 || 31395
47 || 35720
49 || 40425
BUILD SUCCESSFUL (total time: 0 seconds)

Java Pattern of 1 row odd and 1 row even

I want to print a pattern like :
Till now i have been able to achieve only for odd numbers like :
1
3 5 7
-
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
I am a beginner and new learner. please help
I'm not sure what's the expected result since that pattern is not clear, however this might be what you're looking for:
int evenCounter = 1;
int oddCounter = 2;
for (int i = 1; i <= 10; i++) {
boolean even = (i % 2 == 0);
for (int j = 1; j < i; j++) {
System.out.print((even ? evenCounter : oddCounter) + " ");
evenCounter += even ? 2 : 0;
oddCounter += even ? 0 : 2;
}
System.out.println();
}
Result:
1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
14 16 18 20 22 24
19 21 23 25 27 29 31
26 28 30 32 34 36 38 40
33 35 37 39 41 43 45 47 49
If the length of each row matters, then the second for loop should have a different exit condition I suppose
To get the pattern from 3 5 7, this code would do, where MAX_PATTERN_NUM is the first number of the last line of the pattern (in your example's case, MAX_PATTERN_NUM = 15)
for(int i = 3; i <= MAX_PATTERN_NUM ; i+=3)
for(int j = i; j <= (i + 4); j+=2)
System.out.print(j + " ");
System.out.println();
However, I see no logical way of getting the entire pattern using the same nested for loops, so I hope this helps
How about this:
public void printPattern(){
int evenCounter = 2;
int oddCounter = 1; //counters
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt(); //input
}
for(int i = 1; i <= num ; ++i){
if(i % 2 == 0)
evenCounter = addNumbers(i, evenCounter); //print line with evenCounter
else
oddCounter = addNumbers(i, oddCounter); //print line with oddCounter
}
}
private int addNumbers(int i, int counter){
for(int j = 0; j < i;){
if(getIntLength(counter) + j > i) //if the number to long
System.out.print(cut(counter, getIntLength(counter) + j - i) + " "); //output the cut version
else
System.out.print(counter + " ");
j += getIntLength(counter);
counter += 2;
}
System.out.println();
return counter;
}
private String cut(int i, int length){
return Integer.toString(i).substring(0,length); //get substring of int
}
private int getIntLength(int i){
return Integer.toString(i).length(); //get the length of int value
}
It's not so simple, but I don't see an easier way
My answer is based on the assumption that the last 2 is a cut off 21
int n,i,j,o=1,e=2;
System.out.println("enter n:");
n=sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
if(i%2!=0){
System.out.print(o);
o+=2;
}
if(i%2==0){
System.out.print(e);
e+=2;
}
}
System.out.println();
}

Java - vertical integers and palindrome

I stumbled upon an exercise that asked me to reproduce this (that's the expected output):
11111
3456789012109876543
This is a palindrome (at the bottom) where numbers higher that 9 (double digits) have to be written vertical. This sounds complicated to me, and I needed some help.
This is what I did so far, the palindrome:
class Print {
public static void main(String[] args) {
System.out.println("Insert a number from 1 to 100: ");
int input = Read.anInt();
System.out.println("Insert another number from 1 to 100: ");
int output = Read.anInt();
int a = input;
for (int i = a; i < output; i++){
System.out.print(a);
a++;
}
a = input -1;
for (int j = output; j > a; j--){
System.out.print(output);
output--;
}
}
}
Could you help me by explaining how to make sure numbers higher than 9 will be written vertically?
AdamRice: i mean this:
3456789111119876543
01210
But what I've managed to do so far is this mess:
456789101
0
111
1
121110987654
This is all probably because I'm completely ignoring arrays.
Apologies for being a bit slow. After finally understanding the problem, I think I have a solution.
import java.util.Scanner;
public class VerticalText {
public static void main(String[] args) {
Scanner Read = new Scanner(System.in);
System.out.println("Insert a number from 1 to 100: ");
int start = Read.nextInt();
System.out.println("Insert another number from 1 to 100: ");
int end = Read.nextInt();
String numbers = "";
for(int i = start; i <= end; i++)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
for(int i = (end-1); i >= start; i--)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
String row1 = "";
String row2 = "";
char[] chars = numbers.toCharArray();
for(int i = 0; i < chars.length; i++)
{
if(chars[i] == '0')
{
chars[i] = ' ';
}
row1 += chars[i];
i++;
row2 += chars[i];
}
System.out.println(row1);
System.out.println(row2);
}
}
With inputs 5 and 15, it produced the following output:
11111111111
567890123454321098765
Explanation
I build a string of the numbers and if it's less than 10 format it with a leading 0. This extra 0 is just a placeholder. When it comes to printing, we can print a space instead of a zero.

Numbers triangle in Java

I'm trying to write a program that prints out a triangle made of numbers. It should look like that:
1
2 3 4
3 4 5 6 7
4 5 6 7 8 9 0
5 6 7 8 9 0 1 2 3
6 7 8 9 0 1 2 3 4 5 6
In my case it returns negative numbers (876543210-1-2-3...) but it should use only 0-9. I could use modulo n%10, but I don't know how to write that. Any help? Thank you.
import java.util.Scanner ;
public class Triangle {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number: ");
int n = sc.nextInt();
int j;
int i;
int k = n-1;
System.out.printf("n=%d\n\n", n);
for (i=1; i<=(n*2); i=i+2) {
for (j=0; j<=2*n-1; j++) {
if (j < k){
System.out.print(" ");
}
else if (j < (k+i)){
System.out.printf("%d", (n-j));
}
else {
System.out.print(" ");
}
}
k = k-1;
System.out.println();
}
}
}
This is a possible implementation, I modified your index names because it was a little confusing:
public class Triangle {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number: ");
int n = sc.nextInt();
int startNumber = 1; /* First number in the line */
int spaces = n - 1; /* Spaces in the current line */
int numbers = 1; /* Numbers in the current line */
System.out.printf("n=%d\n\n", n);
for (int lineCounter = 0; lineCounter < n; lineCounter++) {
/* Spaces before the numbers */
for (int spaceCounter = 0; spaceCounter < spaces; spaceCounter++) {
System.out.print(" ");
}
for (int numberCounter = 0, number = startNumber; numberCounter < numbers; numberCounter++) {
System.out.printf("%d", (number));
number = (number + 1) % 10;
}
/* Spaces after the numbers */
for (int spaceCounter = 0; spaceCounter < spaces; spaceCounter++) {
System.out.print(" ");
}
System.out.println();
startNumber = (startNumber + 1) % 10;
spaces--;
numbers += 2;
}
}
}
You could create a printTriangle() method like this (explanation follow in the comments):
static void printTriangle(int numLines) {
for (int lineNumber = 1; lineNumber <= numLines; lineNumber++) {
// Print 2 * (numLines - lineNumber) spaces before the first number in the current line
for (int spacesPerLine = 0; spacesPerLine < 2 * (numLines - lineNumber); spacesPerLine++) {
System.out.print(" ");
}
// First line has 1 number, second has 3, third has 5, etc.
int numbersPerLine = (2 * lineNumber) - 1;
// Print the numbers in the current line
// from lineNumber (inclusive) to lineNumber + numbersPerLine (exclusive)
for (int number = lineNumber; number < lineNumber + numbersPerLine; number++) {
System.out.print((number % 10) + " ");
}
System.out.println();
}
}

Categories