so I need to use a method with one parameter to draw a cross whose size is dictated by that parameter. So drawCross(5) would be:
*
*
*****
*
*
I can't seem to get it to work. My code will ask for a number, but then nothing. I'm sure it's probably just me being stupid, but I can't for the life of me figure out what it is. Here's what I have:
import java.util.Scanner;
public class Lab9E1CrossTest {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.print("Number: ");
int n = kbd.nextInt();
drawCross(n);
kbd.close();
}
public static void drawCross(int n) {
int lineCounter = 1, charCounter = 1;
if (n % 2 == 1) {
while (lineCounter <= n) {
if (lineCounter == ((n / 2) + 1)) { // determines if middle line
// by dividing n by two then
// adding 1 (ex. middle of 5
// is 3, so 5/2=2, +1=3)
charCounter = 1;
while (charCounter <= n) { // prints out n number of stars
// on one line
System.out.print("*");
charCounter++;
}
} else {
charCounter = 1;
while (lineCounter != ((n / 2) + 1)) {
if (charCounter == ((n / 2) + 1)) { // if middle char of
// line
System.out.print("*");
} else {
System.out.print(" ");
}
charCounter++;
}
}
System.out.println(); // makes sure prints on new line
lineCounter++;
}
} else {
System.out.println("Error: Number is even.");
}
}
}
I would start by validating the user input at the time you receive it (e.g. make sure it's even before you call drawCross).
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.print("Number: ");
if (kbd.hasNextInt()) {
int n = kbd.nextInt();
if (n % 2 != 0) {
drawCross(n);
} else {
System.out.printf("Please enter an odd #, %d is even%n", n);
}
}
}
Next, I suggest you create a utility method to repeat a specific character n times. You can then draw your cross with the repeating String(s)
private static String repeat(char ch, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(ch);
}
return sb.toString();
}
Something like,
public static void drawCross(int n) {
int mid = (n / 2);
String spaces = repeat(' ', mid);
for (int i = 0; i < mid; i++) {
System.out.println(spaces + '*');
}
System.out.println(repeat('*', n));
for (int i = 0; i < mid; i++) {
System.out.println(spaces + '*');
}
}
Related
Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}
So I was asked to do a code that returns the broken down version of the given number. The output should be like this:
Number to break down: 123045011
100000000
20000000
3000000
0
40000
5000
0
10
1
But what my program does is this:
Number to break down: 123045011
100000001
100000002
100000003
100000000
100000004
100000005
100000000
100000001
100000001
This is my code.
import java.util.Scanner;
public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
int numLength = Integer.toString(num).length();
String numAsString = Integer.toString(num);
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
currentNum += Math.pow(10,numLength - 1);
numberBrokenDown += Integer.toString(currentNum) + "\n";
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
System.out.println(brokeDownNumber(number));
}
}
What should I change/do?
Change your for loop as below -
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
int currentNum2 = currentNum*(int) Math.pow(10,numLength - i -1);
numberBrokenDown += Integer.toString(currentNum2) + "\n";
}
Only one line code change is needed.
currentNum *= (int)Math.pow(10, numLength - i - 1);
In each iteration, 10's power should decrease. So, numLength - i - 1 is needed.
+= is changed to *= because currentNum should be multiplied by 10th power to get desired result.
public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
String numAsString = Integer.toString(num);
int numLength = numAsString.length();
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = num%10;
num = num/10;
if(currentNum ==0) {
System.out.print("0");
}else {
// currentNum += Math.pow(10,numLength - 1);
// numberBrokenDown += Integer.toString(currentNum) + "\n";
System.out.print(currentNum);
for(int j=0;j<i;j++)
System.out.print("0");
}
System.out.println("");
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
brokeDownNumber(number);
}
}
I wrote this code with out number format class.
My Question Is: Is there any way to make this process shorter without Number Format Class.
String num=JOptionPane.showInputDialog("enter number");
Int len=num.length();
String res="";
if (len==4){
res=num.charAt(0)+","+num.substring(1);
}
else if(len==5){
res=num.substring(0,2)+","+num.substring(2);
}
else if(len==6){
res=num.substring(0,3)+","+num.substring(3);
}
else if(len==7){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4);
}
else if(len==8){
res=num.substring(0,2)+","+num.substring(2,5)+","+num.substring(5);
}
else if(len==9){
res=num.substring(0,3)+","+num.substring(3,6)+","+num.substring(6);
}
else if(len==10){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4,7)+","+num.substring(7);
}
System.out.println(res);
Something like the following:
public static void main(String[] args) {
int myInt = 1234567890;
StringBuilder str = new StringBuilder(String.valueOf(myInt));
int length = str.length();
int count = 0;
for (int i = length; i > 0; i--) {
count++;
if (count % 3 == 0 && count != length) {
str.insert(i - 1, ",");
}
}
System.out.println("Formatted Number: " + str);
}
I have a java problem that I don't know how to solve the program is :
two number must got from user n,k.
I need to find a permuation of numbers from 1 to N such that the difference between two items >=k for example :
we get the numbers (n = 5 and k = 2 )
and the answer must be 1,4,2,5,3 :
and for (n=2 and k = 2) there is not answer because the difference between 1 and two is 1(1,2 or 2,1).
I hope you understand what I want.
and I write some codes that are wrong:
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int n = user_input.nextInt();
int k = user_input.nextInt();
int a ;
if (n%2==0) a = (n-2)/2; else a = (n-1)/2 ;
if (k!=a) {System.out.println("Impossible"); return;}
int h = k+1;
int value = 0;
int t = 1;
boolean b = true;
String res = "1 ";
while (value<n-1) {
value++;
if (b){
t = t + h;
res = res + t + " ";
b = false;
}else {
t = t-k;
res = res + t + " ";
b = true;
}
}
System.out.println(res);
}
Here is the code
public class HelloWorld{
public static void calculationMethod(int n, int k) {
if(n<2 || n/2 < k) {
System.out.println("Impossible");
return;
}
else {
int i = (int)Math.ceil(n/2.0);
int j = n;
int start = i;
boolean flag = true;
while(i>=1 || j>start) {
if(flag) {
System.out.print(i + " " );
i--;
flag = false;
}
else {
System.out.print(j + " " );
j--;
flag = true;
}
}
}
}
public static void main(String []args){
calculationMethod(7,3);
}
}
The idea is to divide your range(n) in half. If k>n/2 then it is not possible to construct any such sequence.
If that is not the case, then have 2 pointers one at the middle of your range and one at the end of the range. and print them alternatively decrementing both pointers until u reach the beginning.
Feel free to improve the code.
public void calculationMethod(int n, int k) {
ArrayList<Integer> intList = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int a = i;
int b = i + 2;
if (!intList.contains(a) && a<=n) {
intList.add(a);
}
if (!intList.contains(b) && b<=n) {
intList.add(b);
}
}
String mValues= TextUtils.join(",",intList);
Log.i("values", mValues);
}
I'm working on a code which will count how many are the groups with the same number.
For example:
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
So far I've come up to this code:
package Numbers;
import java.util.*;
public class Numbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int strI ;
strI = scan.nextInt();
int[] a = {strI};
System.out.println(sum(a));
System.out.println("length = "+a.length);
}
public static in sum(int[] a){
int sum = 0;
int last = 0;
for (int i = 0; i < a.length - 1; i++){
if(a[i] == a[i + 1] && last != a[i + 1]){
sum++;
}
last = a[i];
}
return sum;
}
}
My problem is that the inputted number will register as 1 index. is it possible to enter a series of number that will go to different indexes?
This is easiest done by converting it to a string so you don't have to deal with place value. After all, you only care about the characters themselves.
public static void main(String[] args){
// Get number n... Assuming n has been set to the int in question
int n = ...; //Fill in with whatever int you want to test
String s = n + "";
char same = ' ';
int consec = 0;
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i+1)){
if(same == ' ')
consec++;
same = s.charAt(i);
}
else{
same = ' ';
}
}
System.out.println(consec);
}
First, you can get the count of consecutive digits with something like
public static int sum(int a) {
String strI = String.valueOf(a);
int count = 0;
boolean inRun = false;
for (int i = 1; i < strI.length(); i++) {
if (strI.charAt(i - 1) == strI.charAt(i)) {
if (inRun) {
continue;
}
inRun = true;
count++;
} else {
inRun = false;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = { 11022, 1100021, 12123333 };
for (int val : arr) {
int count = sum(val);
String group = "groups";
if (count == 1) {
group = "group";
}
System.out.printf("%d = %d %s with the same number%n", val, count, group);
}
}
Output is the requested
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
As for your second question, you might read Integer into a List - Java arrays are immutable,
List<Integer> al = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
al.add(scan.nextInt());
}
Integer[] arr = al.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));