How to print strings after inputting - java

User inputs int number. Based on that number user can input the same number of strings. For example:
Input:
3
Dave
John
Ben
Output:
Hello, Dave
Hello, John
Hello, Ben
Currently it performs output immediately as only first string is being input:
3
Dave
Hello, Dave
John
Hello, John
Ben
Hello, Ben
What should I change? Can't get it right by myself
public class HelloStrangers {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String stringNumber = scanner.nextLine();
int number = Integer.parseInt(stringNumber);
if (number < 0) {
System.out.println("Seriously? Why so negative?");
} else if (number == 0) {
System.out.println("Oh, it looks like there is no one here");
} else {
int i = 0;
for (i = 0; i < number; i++) {
String string = scanner.nextLine();
System.out.println("Hello, " + string);
}
}
}
}

Store the input. Print it later.
String[] list = new String[number];
for (int i = 0; i < number; i++) {
String string = scanner.nextLine();
list[i] = string;
}
for (int i = 0; i < number; i++) {
System.out.println("Hello, " + list[i]);
}

You'll need to store the strings in an array and then loop through another loop after saving each one:
String[] strings = new String[number];
for (int i = 0; i < number; i++) {
String string = scanner.nextLine();
strings[i] = string;
}
for (int i = 0; i < number; i++) {
System.out.println("Hello, " + strings[i]);
}

Related

Finding multiple set of given words in a paragraph array

I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)
Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}

Problem with this error : Exception in thread "main" java.lang.NumberFormatException: For input string: ""

This is the problem wherein, we will subtract two numbers using 9's complement.
import java.io.*;
public class NinesComplement {
public static void main(String[] args)throws java.io.IOException {
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
while (true) {
System.out.print("Enter Minuend: ");
int min = Integer.parseInt(br.readLine());
System.out.print("Enter Subtrahend: ");
String sub = br.readLine();
int max = Integer.toString(min).length();
for (int i = 0; sub.length() < max; i++) {
sub = 0 + sub;
}
String [] subArr = sub.split("");
int[] num = new int[subArr.length];
for (int i = 0; i < subArr.length; i++) {
num[i] = Integer.parseInt(subArr[i]);
}
int[] n = new int[num.length];
for (int i = 0; i < num.length; i++) {
for (int ii = 0; num[i] < 9; ii++) {
num[i]++;
n[i]++;
}
}
String str = "";
for (int i = 0; i < num.length; i++) {
str += Integer.parseInt(Integer.toString(n[i]));
}
int add = Integer.parseInt(str);
String ans = Integer.toString(min + add);
if (ans.length() > max) {
String temp1 = ans.substring(0, 1);
String temp2 = ans.substring(1, ans.length());
int fin = Integer.parseInt(temp2) + Integer.parseInt(temp1);
System.out.println("Answer: " + fin);
} else if (ans.startsWith("9") && ans.endsWith("9")) {
System.out.println("Answer: 0");
}
System.out.print("Do you want to try again? \n[y][n]: ");
String choice = br.readLine();
if (choice.equals("n")) {
System.out.println("Thank you!!!");
System.exit(0);
}
}
}
}
Exception in thread "main" java.lang.NumberFormatException: For input
string: ""
You're just trying to parse an empty string into a number. You should always validate user input before trying to use it :).
Add a pre-condition (just an if statement check) before using the input and print a nice message to the user if the input was bad, and just go back to waiting for more good input.
Also, to debug this issue, just make your life easier and add some print statements surrounded by quotes before you try and use the user input so you can see it.

Removing a user defined element from a user defined string array [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have an assignment due in about 6 hours and I really need help. I stayed up all night working on this but I can't seem to figure it out.
Basically what I need to do is, I have a user defined array. I'm supposed to take that array and manipulate that string into a variety of things. I've gotten most of it but I can't seem to remove a user defined element in the user defined string. I've tried using a for loop to try and find the specific character that the user wants to remove but I can't seem to get it to compile or write properly. This is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringManipulator {
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equals("Print Reverse") || choice.equals("print reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equals("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equals("Replace Single") || choice.equals("replace single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
else if (choice.equals("Remove") || choice.equals("remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
char charRemove = ridOf2.charAt(0);
for (int i = 0; i < array.length; i++) {
if(userStr.charAt(i) != ridOf2) {
userStr += userStr.charAt(i);
}
}
}
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
The only section that i'm actually worried about at this moment is the
else if(choice.equals("Remove")
section of the code.
Give this a shot explanation further down
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equalsIgnoreCase("Print Reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equalsIgnoreCase("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equalsIgnoreCase("Replace Single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
This is the section I changed .equalsIgnoreCase compares them ignoring case as expected. Then I made sure the user only entered one char and if more ignore them. Then changed the char remove to be a string of only the first char(because you cannot replace with a char it needs to be a string) then I replaced the char to be removed in the string with nothing essentially removing it and set the user string to the new user string
else if (choice.equalsIgnoreCase("Remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
String charRemove = String.valueOf(ridOf2.charAt(0));
userStr = userStr.replaceAll(charRemove, "");//This will replace the first char the enter with nothing
}
End of section
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
String's replace should do it -
public class Test
{
public static void main(String [] args) {
String s = "Hello World";
s = s.replace(" ", "");
System.out.println(s);
}
}

Converting on input int to string & finding correct number

I am trying to convert the input of a Int directly to a String.
I am also trying to make it so the program will find the correct number in a credit card sequence to make it correct.
For example if I input a incorrect credit card number, the program finds a way to change the numbers so it becomes correct.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input a credit card number to validate");
String cc = in.nextLine();
validateCreditCardNumber(cc);
String convertedCC = (cc);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
That is all my code, but what i am trying to fix is when I initialize cc, i can convert to a string to be later used.
My issues:
int to string has been fixed,
converting to correct CC number has not been fixed.
Can you just get it as a string directly?
String cc = in.nextLine();
Use following code instead of int cc = in.nextInt();
String cc = in.next();
You never use the int version of the scanned input. Instead of making cc an int then converting to a string, just initially make it a string... something like this:
String cc = in.nextLine();

Java: Printing trailing spaces

I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.
The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.

Categories

Resources