Java - vertical integers and palindrome - java

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.

Related

How to separate integers using arrays?

I am a noob at programming so I might have trouble with some key terms.
I'm trying to write a program where a user types in a minimum number and a maximum number and it generates a random number. After that I want to know how many even numbers and odd numbers are in the random generated number. I was able to successfully complete the first part but I am having trouble detecting how many even and odd numbers are in the random generated number.
SAMPLE OUTPUT:
Ex:
Random generated number is: 478,099
# of even digits: 2
# of odd digits: 3
I tried creating local variables that did not work, I want to use a switch case statement but I am having trouble. For now I used a for loop but I want to use a switch case.
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
}
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
I can't look at the whole number separately.
**EDIT 1**
import java.util.Scanner;
import java.text.DecimalFormat;
public class MyClass
{
public static void main(String args[])
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
int even = 0; int odd = 0;
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
System.out.println("Even:" + even);
System.out.println("Odd: " + odd);
}
}
}
I have gotten it to detect the even numbers and the odd numbers now I am curious to know if there is a way to do it without having the the two variables (odd, even).
You are not dividing the value l by 10. Which is why it is going into a infinite loop.
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
if((l % 10)%2==0) // this line is changed
{
even++;
}
l = l/10; // this line is changed
}
}
}
Also, if you are checking for even, you have to do ...%2 == 0. Find your errors fixed in the code above.
EDIT: you can also calculate the odd numbers in the same loop, like this:
if((l % 10)%2==0) // this line is changed
{
even++;
}
else
{
odd++;
}
EDIT3: The code was supposed to go inside the method, not replace the method.
I do not see any use case for a switch case here, but it can be accommodated like this:
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
Hope this helps. Good luck.

How to make this programm to count the odd and even numbers in an array?(eclipse)

Thanks for the answers guys, didn't expect getting answers so fast.
Ok so in this code at the final stage it is meant to count how many odd and evens numbers there are in the array length you decide.
If you for example type in 10 it prints out 10 random numbers between the intervall of 0-999 and then it seperates the odd and even numbers
In the last stage it's meant to calculate how many odd and even numbers there are like ''out of the 10 numbers 4 of them were even numbers and 6 were odd numbers''
Right now in the last stage it just prints out numbers randomly and doesen't calculate how many odd and even numbers there are. I don't know how to fix it.
I have ran out of ideas about it so hopefully someone here can make it work properly.
import java.util.Scanner;
public class Uppgift4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length;
while (true)
{
System.out.print(" \n\nHow many numbers do you want in the intervall 0-999?(turn off with -1 or 1000):");
length = scan.nextInt();
if (length>999)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
if (length<0)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
System.out.println("\n Here are the random numbers:");
int [] ar1 = new int[length];
for(int i = 0; i < length; i++) {
ar1[i] = (int)(Math.random() * 1000);
{
System.out.print(" "+ar1[i]);
}
}
System.out.println(" \n");
System.out.println(" Here are the numbers divided between even and odd numbers:");
System.out.print(" ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.print("- ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 != 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.println(" \n");
System.out.print(" Of the above numbers "+ length + " so ");
System.out.print("where ");
for(int evennumbers = 1 ; evennumbers < length ; evennumbers++)
{
if(ar1[evennumbers] % 2 == 0)
{
System.out.print(evennumbers+" ");
}
}
System.out.print(" of the numbers even and odd numbers were ");
for(int oddnumbers = 1 ; oddnumbers < length ; oddnumbers++)
{
if(ar1[oddnumbers] % 2 != 0)
{
System.out.print(oddnumbers+" ");
}
}
}
}
You need to count the number of even and odd number:
int even = 0;
int odd = 0;
// Loop through the final array
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
even++;
} else {
odd++;
}
}
Even simpler:
for(int i = 0 ; i < length ; i++)
{
odd += (ar1[i] % 2)
}
even = length - odd;
just make two global variables to count the odd and even and put them into the condition where you are checking for odd and even.
code
Why not just make use of bitwise AND and remove those conditionals like so:
int odd = 0;
int even = 0;
for(int i=0;i<length;i++){
odd+=ar1[i]&1;
even+=((ar1[i]+1)&1);
}
you can use this way , very simple
public static void main(String []args){
Integer[] arr = new Integer[] { 1,2,3,4,5};
int oddCount =0; int evenCount=0;
for ( int i=0; i< arr.length ;i++){
if( ( arr[i] % 2) == 0 )
evenCount++;
if( arr[i] % 2 != 0 )
oddCount++;
}
System.out.println( "oddCount in Array :" + oddCount + " EvenCount in Array : " + evenCount);
}

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Can't find a bug in my code

I am trying to finish my assignment but I can't seem to find the bug in my code. It is not a compiler error, and I have been looking at it for hours.
This code is for a game called Mastermind. These are the guidelines (a bit long, I know, but all necessary info for the assignment):
Computer chooses a random 4 digit number, and no digit may repeat itself. (ex: 0462, 2930, 6103 are valid numbers)
The user's goal is to try and guess the computer's chosen number
Once the user makes a guess, the computer will tell the user how class that guess was by giving the following information:
The number of digits matched perfectly (are in the right place)
The number of digits that are off place
When you scan the input from the user, use a String to store it. Your
program must have 4 methods in addition to the main method:
One method named isValidNumber that checks if a given String corresponds to a valid 4 digit number.
One method named perfectMatches that returns the number of perfect matches between two Strings that represent valid 4 digit numbers.
One method named offPlaceMatches that returns the number of ‘off place’ matches between two Strings that represent valid 4 digit
numbers.
One method named generateRandomValidNumber that returns a String that represents a random valid 4 digit number.
Hint: Generate a random 4 digit number by generating a random single
digit 4 times and concatenating them. Then using your isValidNumber
method, check if this String you created is valid. If it is not,
repeat the first part and pick 4 new random digits.
This is my code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
//string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while(!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if(number.length() != 4) {
return false; }
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if(!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for(int j = 0; j < 4; j++)
if(numberArray[j] == c)
count++;
if(count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < one.length(); i++) {
if(one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i == 0)
continue;
if(one.charAt(j) == two.charAt(i)) {
counter++;
}
if(j == i -1) {
i++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while(!validNumber) {
for(int i = 0; i < 4; i++) {
char c = (char) (int) (Math.random() * (9));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
There's a problem in the generateValidNumber method.
You are not re-initializing newNumber when you try to find a new random number.
Changing it to the following function should result in the successful execution of the program. Also, multiply the random number with 10 to get an number in the range [0.0, 10.0) (0 included and 10 excluded)
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = null;
while(!validNumber) {
// add this line
newNumber = "";
for(int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
But there are a few logical errors in the code. For e.g., you are generating a new number everytime a user guesses an invalid number.
Update:
I made a few changes to your code. This should help you get going.
import java.util.Scanner;
public class MastremindString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out
.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
// string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while (!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: "
+ offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if (number.length() != 4) {
return false;
}
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if (!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for (int j = 0; j < 4; j++)
if (numberArray[j] == c)
count++;
if (count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
if (one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
for (int j = 0; j < two.length(); j++) {
if (one.charAt(j) == two.charAt(i) && i != j) {
counter++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while (!validNumber) {
newNumber = "";
for (int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if (isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
It appears that you are generating a new number on every cycle. The best way to fix this is to not assign to the validNumber variable within main(...) on every loop.
Since you get to the point of "What is your guess?" and you enter a number, but then nothing happens (which presumably means you do not get past the two lines following the first guess=input.nextLine(); call), the function to check first is the generateValidNumber(); function. Second, check your perfectMatches(...); function. You can add System.out.println("blah"); calls to see how far your code gets (as a very crude debugging tool).
I'm assuming you're using Eclipse and in an introductory programming course. An important subject often overlooked in programming courses is how to use a debugger to help you troubleshoot problems. If any of your classmates, lab assistants, or fellow students further along in your major can take 15-30 minutes to sit down and show you how to use the debugger, it will help you through the rest of your programming career.
If not, there are a lot of tutorials you can follow to get familiar with Eclipse's debugger.
To start off, double-click along the left of your code, usually just left of the line numbers. This will add a break point, which will pause your program when it reaches. Add a break point at each of your methods besides main and make sure that all the methods you think should be called are actually called.
When your program is at a break point, you can also take a look at the value of variables in the "Variables" view. If one of them has an unexpected value, you may have found your culprit.
There is a resume button you'll have to hit to resume program execution when you're done at a given break point. It should be next to the Pause and Stop buttons in the top bar by default, and is easy to confuse with the Run button.
First: You never call isValidNumber to check if the user's input is valid. You should call this method and if the number is invalid, the program should terminate or prompt the user for a new number

How to find a specific number from a user set upperbound and lowerbound in java

The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}

Categories