How do I add white spaces in Java Array? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm kind of new to this stuff, but what i want to do is just print out 00s from an int array that i created. I used a stringBuilder() to get rid of the commas and stuff. Now when I print out the numbers, they must have a space after every third 0 (a total of 11 0s). How do I do that? I only get a space after every 0 :-(.
here is what I got so far.
public class AccountNumber {
private int[] digits = new int [11];
// Methods Returns a string representation
public String toString() {
StringBuilder builder = new StringBuilder();
for (int value :digits) {
builder.append(value + " ");
}
String text = builder.toString();
return text;
//return Arrays.toString(digits);
}
public AccountNumber ( boolean random ){
}
}
The output I want is 000 000 000 00
I have another (main) class which creates the object for me. That's where the printing should happen.
public class Test1 {
public static void main (String [] args) {
//Random rand = new Random(false);
AccountNumber acc = new AccountNumber(false);
System.out.println(acc.toString());
//AccountNumber.AccountNumber();
}
}
Thank you

You are trying to pretty print 11-digit account number on your Account class. You want to insert space after each 3 digits. If my assumptions are correct, you just need a counter to see which digit you're on and test if that digit can be divided by three:
int index= 0;
for (int value :digits) {
builder.append(value);
if (index %3 == 0) {
builder.append(" ");
}
++index;
}
This could be written in more clear way by using classic for loop, but I don't know which type your digits field is.

Related

How to use return in a java function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
My function is to make the code below print out 'Math' at an even number and 'English' at an odd number and repeat the process five times.
public static String[] subject() {
String[] subjects = { 'Math', 'English' };
int i=0;
while (i<5) {
if (i%2==0) {
System.out.println(subjects[0]);
}
else {
System.out.println(subjects[1]);
}
i++;
}
return subjects;
}
public static void main(String[]args) {
for(int n=0; n<5; n++) {
subject();
}
Originally it's double quotes, but I don't know how to do it, so I put single quotes.
It works, but I don't know how to use the return exactly.
I understand placing variable after return makes it the same type, ends the method and calls the result.
so why should I write a variable name, instead of writing the name of the function.
sorry im not good at English so had to refer to a translator to help
For this requirement, you should declare the return type as void as you just want to print the elements from the array and you are not using the returned array.
You need to remove the loop from inside main because it's already there in your method, subject.
0 is neither an odd number nor an even number. So, you should start with i = 1 and the terminating condition of the loop should be i <= 5.
In Java, single quotes are used to enclose char literals. To enclose String literals, you need to use double-quotes. Note that many languages, especially scripting languages and SQL, support enclosing String literals using single quotes.
Demo:
public class Main {
public static void subject() {
String[] subjects = { "Math", "English" };
int i = 1;
while (i <= 5) {
if (i % 2 == 0) {
System.out.println(subjects[0]);
} else {
System.out.println(subjects[1]);
}
i++;
}
}
public static void main(String[] args) {
subject();
}
}
Output:
English
Math
English
Math
English

How to get the desired output in JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If there is a given
Inputs
String "abcdaa/efgh/hidjk/lmno/pqrs/tuvw" and if
int slashCounter=3,
The desired Output should be -
Output: abcdaa/efgh/hidjk/lmno
(Basically if slashCounter=3 only alplabets upto 4th '/' is allowed. From fourth '/'everything is ignored. Below is the few Input and Output. (There may be any number of alphabets between '/' to '/'). Below is few more inputs
Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=2
Output: aaabcd/efgh/hidjk
Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=4
Output: aaabcd/efgh/hidjk/lmno/pqrs
Could someone help me with the logic of this in JAVA. Thanks in advance.
This is how you do.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// till how much we want the string
int display = sc.nextInt();
// splits the String when "/" is encounter and then stores it in 0 index and then increases the index
String aplhabets[] = input.split("/");
// to add the String we want
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i <= display; i++) {
sb.append(aplhabets[i]+"/");
}
// as we dont want the last "/" of the String we just print from 0 to string length - 1, this will remove teh last "/"
System.out.print(sb.substring(0, sb.length()-1));
}
Output:
aaabcd/efgh/hidjk/lmno/pqrs/tuvw
2
aaabcd/efgh/hidjk
String aplhabets[] = input.split("/") this splits the String and puts it in the array whenever / is encounter.
sb.substring(0, sb.length()-1) this cause when we were appending String builder from he loop it's adding / in the end.
So in order to remove last / we do sb.substring(0,sb.length-1) where first parameter is start index and second index is end index
in substring(int start, int end) start in inclusive and end is exclusive.
this is how you do the problem. Suggest you learn how to use arrays and String manipulation. this will surely benefit you.

How to clarify whether the user's input was a binary number? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was required to make a code that accepted a binary number (1's and 0's) and then counted how many ones were in that binary number. My code fulfills this purpose.
The second part of the exercise is this: if the user enters a number that is NOT binary, I must output that there is an error and keep prompting the user until they give a binary number.
Can someone show me how to incorporate this? I have tried several times but cannot make it click. Thanks! Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in);
int i = 0, count = 0;
String number;
System.out.println("Please enter a binary number.");
number = scan.next();
String number1 = "1";
while ((i = number.indexOf(number1, i++)) != -1) {
count++;
i += number1.length();
}
System.out.println("There are "+ count + " ones in the binary number.");
}
}
You already know how to find all of the 1's; you should be able to do something similar to find all of the 0's.
If the sum of those two counts is not the length of the string, there must be at least one illegal character in it.
If you use the parseInt method you can do
Integer.parseInt("1100110", 2) returns 102
or in your case
int intVal = Integer.parseInt(number, 2);
as per the javadocs
Throws:
NumberFormatException - if the String does not contain a parsable int.

How does one go about doing so [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a method called multiConcat that takes a String and an integer as parameters. Return a String made up of the string parameter concatenated with itself count time, where count is the integer. for example, if the parameters values are “ hi” and 4, the return value is “hihihihi” Return the original string if the integer parameter is less than 2.
What i have so Far
import java.util.Scanner;
public class Methods_4_16 {
public static String multiConcat(int Print, String Text){
String Msg;
for(int i = 0; i < Print; i ++ ){
}
return(Msg);
}
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
int Prints;
String Texts;
System.out.print("Enter Text:");
Texts = Input.nextLine();
System.out.print("Enter amount you wanted printed:");
Prints = Input.nextInt();
System.out.print(multiConcat(Prints,Texts));
}
}
Just a few hints:
concating strings can be done this way: appendTo += stuffToConcat
repeating an operation n times can be done with a for-loop of this kind:
for(int i = 0 ; i < n ; i++){
//do the stuff you want to repeat here
}
Should be pretty simple to build the solution from these two parts. And just in case you get a NullPointerException: remember to initialize Msg.
Try this:
public static String multiConcat(int print, String text){
StringBuilder msg = new StringBuilder();
for(int i = 0; i < print; i ++ ) {
msg.append(text);
}
return msg.toString();
}
I have used StringBuilder instead of a String. To know the difference, give this a read: String and StringBuilder.
Also, I would guess you are new to Java programming. Give this link a read. It is about Java naming conventions.
Hope this helps!

How to get started with writing a program that consists of three classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a program that consists of three classes. The first class will be the actual program.
The second class will simply convert a string to lower case.
The third class will have three methods: I have been working on this assignment but i need some help. All my previous assignments have been only in one string. So i'm not sure how to get started with this. I will list what i have tried so far.
import java.io.*;
public class A3BE2300780
{
BufferedReader in = getReader ("input.txt");
private static class LowerCase {
public static String convertToLowerCase(String input) {
if (input==null) return "";
return input.toLowerCase();
}
}
public static class ThirdStringManip{
//This method will trim the white space from the
//beginning and end of the string
public static String trimmed(String s){
if (s == null){
return "";
}
return s.trim();
}
//This method will return a trimmed string of size len
public static String trimmed(String s, int len){
String retVal = ThirdStringManip.trimmed(s);
if (len > retVal.length()){
len = retVal.length();
}
return retVal.substring(0,len);
}
//This method will convert all double spaces to a single space
public static String squeeze(String s){
return s.replace(" ", " ");
}
}
//This method will read strings from the input file
//and perform manipulations on each string. The results of the
//manipulations are displayed in the text area
private void displayManipulatedStrings() throws Exception{
while(loop)
{
//Get the next line in the file
String curString = s.nextLine();
//Trim and Squeeze
System.out.print ( "Trim & Squeeze: " + ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)) + "\n");
//Trim, Squeeze, and Shorten to 10 characters
System.out.print ( "Trim, Squeeze, Shorten to 10: " + ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),10) + "\n");
//Trim, Squeeze, lower-case and shorten to 20 characters
System.out.print ( "Trim, Squeeze, Shorten to 20, lower-case: " + toLower(ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),20)) + "\n");
System.out.print ( "\n");
}
}
}
Ok so ... Some JAVA book & online tutorials will help a lot...
To start
Main class is where your main method is. So create a new empty class and add your main method to it.
public static void main (String[] args) {
//inside you can put some logic
}
Create another class and i.e StringConversion and insert a simple method iniside for example
class StringConversion {
private String lowerCaseString = "";
public String stringConversion(String somestring) {
lowerCaseString = somestring.toLowerCase();
return this.lowerCaseString;
}
}
Then create a third class with whatever methods you require
In your main method you can do
StringConversion lowerCaseString = new StringConversion();
String lowerCase = lowerCaseString.stringConversion("SOME STRING");
Then you can just print out the lowerCase string ;)
ALSO NOTE: MEGA ULTRA UBER IMPORTANT
When asking question on StackOverflow do not ASK US to do something for you, You have to show effort and show us what you tried by either explaining nicely or showing to us what have you done and why it didn't work. You can not just dump a homework question and pray that someone will do it for you. it just doesn;t work that way, and often you will find your questions to be locked and closed

Categories