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!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
If i have an input smt. like that:
1,10;3,3;4,1. Lets say String input.
How can I split it in ";", so the result could be like this:
[1,10]
[3,3]
[4,1]
Thanks!
I think you want to do something like this.
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
//your input is 1,10;3,3;4,1
input = scanner.next();
String[] splitted = input.split(";");
//save the new list or array
ArrayList list = new ArrayList();
for (int i = 0; i < splitted.length; i++) {
System.out.println(splitted[i]);
//for later usage
list.add(splitted[i]);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
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 5 years ago.
Improve this question
I have a problem in my assigment, I want to invert a word like "Indonesia" to "aisenodnI".
public static void main (String[]args){
balik();
}
public static void balik (String nama){
for ( i>=nama.Length-1 ; i=0 ; i-- ){
balik = balik + nama.Length();
System.out.print(balik);
}
}
You can use StringBuffer or StringBuilder for this task, StringBuilder would be my choice since its more efficient. its not thread safe so multiple threads can call its methods simultaneously.
String reversedString = new StringBuilder(originalString).reverse().toString()
If you prefer not to use API support you can do something like this
static String reverse(String stringIn) {
char[] cArr = stringIn.toCharArray();
for (int i = 0; i < cArr.length/2; ++i){
char c = cArr[i];
cArr[i] = cArr[cArr.length-1-i];
cArr[cArr.length-1-i] = c;
}
return new String(cArr);
}
If only reversing of the string is needed then you can go with the below method.
String name= "India";
String reverseString = new StringBuffer(name).reverse().toString();
System.Out.Println("reversed sstring is "+reverseString );
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 8 years ago.
Improve this question
So I am trying to prompt the user to enter any words into a string. Then I want to prompt them to count the number of occurrences for whatever letter they want to count. So if they enter words in a string like "this is a test" and they search "t" for example, the return would be 3 t's in the string "this is a test". I am a little confused as to where to go from here...
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
String s = "";
System.out.print("Enter a string of words or type done to exit: ");
inputValue = input.readLine();
System.out.print("Which letter would you like to count: ");
s = input.readLine();
int counter = 0;
I am thinking about maybe doing a for loop and do something like counter++.
Answer provided by Jean above is correct but I would like use a different method to calculate number of occurrence of a character in a String.
String string = "this is a testing string";
int count = string.length() - string.replaceAll("t", "").length();
Or
int counter = string.split("t").length - 1;
You would need to escape meta characters if you are to check character like $.
Using Apache commons-lang you could simply do
int counter = StringUtils.countMatches(s, intputValue);
But if you really want to code it, then you could use
public int count(String fullString, char valueToCount)
{
int count = 0;
for (int i=0; i < fullString.length(); i++)
{
if (fullString.charAt(i) == valueToCount)
count++;
}
return count;
}
Another solution would consist of replacing everything in your string except the input char and return the length of the trimmed string.
return s.replaceAll("[^" + inputValue + "]", "").length();
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.
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 having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.
public static void validateData() throws IOException{
File myfile = new File("gradeInput.txt");
Scanner inputFile = new Scanner(myfile);
for (int i=0; i<33; i++){
String studentId = inputFile.next();
String toBeDouble = studentId;
Double fromString = new Double(toBeDouble);
if (fromString<0||fromString>99999){
System.out.println();
}
Any help would be greatly appreciated. Thanks a lot!
Edit: Here's what I get if I try to run the program.
Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.valueOf(Double.java:475)
at java.lang.Double.<init>(Double.java:567)
at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
at Paniagua_Grading.main(Paniagua_Grading.java:6)
Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.
while(inputFile.hasNext()) {
if(inputFile.hasNextDouble()) {
// the next token is a double
// so read it as a double
double d = inputFile.nextDouble();
} else {
// the next token is not a double
// so read it as a String
String s = inputFile.next();
}
}
This kind of convenience is the main reason to use Scanner in the first place.
You could try something like the method below, which will check if a string contains only digits -
private static boolean onlyDigits(String in) {
if (in == null) {
return false;
}
for (char c : in.toCharArray()) {
if (Character.isDigit(c)) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(onlyDigits("123"));
System.out.println(onlyDigits("123A"));
}
The output is
true
false