How to multiply a String by an Integer? - java

I know there's some way to change a string into an integer but it's not really working out for me when I try to do it.
I was asked to take in an integer 'n' and 'a' string 's' and print 's' 'n' times
Here's my code and my main question / question is how do I easily turn the string into an integer so I can multiply the two together:
public static void main(String args[])
{
System.out.println("Enter the number of times you want to print a string");
Scanner n = new Scanner(System.in);
int x = n.nextInt();
System.out.println("Enter the string you want printed");
Scanner y = new Scanner(System.in);
String s = y.nextLine();
}

You only need one Scanner, and if I understand your question then you might use a loop like, also an int n.
System.out.println("Enter the number of times you want to "
+ "print a string");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
for (int i = 0; i < n; i++) {
System.out.print(s);
}
System.out.println();
Of course, you could put the loop in a method like
private static String multiply(String str, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
Then you could call it like,
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
System.out.println(multiply(s, n));

Related

Add 1st and Last digit of a number

I am trying to add the 1st and last digit of a no but after the programs gets to while loop it starts asking for more inputs,like an infinite loop .
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
first=n[i]/10;
}
System.out.println(first+last);
}
This is how I did it.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String temp = t+"";
String[] arr = temp.split("");
int x = Integer.parseInt(arr[0]) + Integer.parseInt(arr[arr.length - 1]);
System.out.println(x);
}
That is because you are not updating the value of n[i] with every iteration.
This is my proposed solution for your while loop:
while(n[i]>=10){
n[i]=n[i]/10;
}
first = n[i]
In while loop you need to update the value of n[i] by using n[i]=n[i]/10; which is causing while loop to become infinite loop
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
n[i]=n[i]/10;
}
first=n[i]/10;
System.out.println(first+last);
}

Java exception error for input string

I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}

Scanner String Confusion

The Programm is supposed to let me enter a value a and a string. While it lets me input he integer when it comes to the string, it prints the question but does not let me enter anything.
import java.util.Scanner;
public class PrSumN {
public static void main(String args[]) {
System.out.println("Enter a value");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int sum = 0;
int pr = 1;
System.out.println("Do you want the sum of the numbers or the products of the numbers?");
String answer = sc.nextLine();
//Itdoesnotletmeinputmystringatthispoint
if (answer == "sum") {
sum(a, sum);
} else {
product(a, pr);
}
}
public static void sum(int a, int sum) {
for (int i = 0; i < a; i++) {
sum = sum + (a - i);
}
System.out.println("The sum of the numbers is " + sum);
}
public static void product(int a, int pr) {
for (int i = 0; i < a; i++) {
pr = pr * (a - i);
}
}
}
After you call int a = sc.nextInt(); you enter an integer in the console and press enter. The integer you entered gets stored in a, whereas the newline character (\n) is read by your String answer = sc.nextLine(); and so it doesn't accept a string from you.
Add this line
sc.nextLine(); // Will read the '\n' character from System.in
after
int a = sc.nextInt();
Another method: You can scan for a string instead of an int and get a by parsing for int:
try {
int a = Integer.parseInt(sc.nextLine());
}
catch (ParseException ex) { // Catch
}
On another (side) note, do not use if (answer=="sum"), instead you would want to use
if (Object.equals (answer, "sum")
Refer to this.
After this line:
int a = sc.nextInt();
Add this:
sc.nextLine();
The reason you need to add sc.nextLine() is because nextInt() does not consume the newline.
Alternatively, you may scan for a String and parse it to the respective type, for example:
int a = Integer.parseInt(sc.nextLine());
Add: And something not related to your primary question, when comparing the value of a String, use .equals and not ==.
We use == to compare identity, so it should be:
if (answer.equals("sum"))

Java code to encrypt a given sting

I want a java code to encrypt a given string using 2 main strings like below
s1 = "qwertyuiopasdfghjklzxcvbnm";
s2 = "mnbvcxzasdfghjklpoiuytrewq";
If our input string is "mnb", then it is compared with s2 and the same index in s1 is added 3 then output will be "rty" but I am not getting proper output.
Can any one help me to solve this problem?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for(int i=0;i<s2.length();i++){
if(input.charAt(i)==s2.charAt(i)){
out+=s1.charAt(i+3);
}
System.out.println(out);
}
sc.close();
}
You almost had the solution! The problem is when you input one of the last 3 characters of s2 you'll have to use the modulo operator (when the position gets larger than 25 you will reach the end of the string and have to start searching at the beginning!)
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
int position = s2.indexOf(input.charAt(i));
position = (position + 3) % 26;
out = out + s1.charAt(position);
}
sc.close();
}
In order to avoid wrong user input you should check the position if it's -1 (if the character is not found in s2) and handle that case properly (exception/outprint + break in the loop)
You need an extra loop to check which character matches from s2 string.Other than that,you will have to use modulo operator to avoid ArrayIndexOutOfBound.
Try this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input, out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (input.charAt(i) == s2.charAt(j)) {
out += s1.charAt((j + 3)%26);
}
}
}
System.out.println(out);
sc.close();
}
UPDATE
As pointed in comment by #ParkerHalo,to handle ArrayIndexOutOfBound,you can use modulo operator like this
out += s1.charAt((j + 3)%26);

Error when looping on keyboard input

I have a loop that is supposed to store information into an array of objects, but for some reason, it always skips the first input.
public class GerbilData {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("How many different food items do the gerbils eat?");
int n1 = keyboard.nextInt();
Food[] gerbilFood = new Food[n1];
String temp;
int temp2;
int count = 1;
for (int a = 0; a < n1; a++){
gerbilFood[a] = new Food();
}
int j = 0;
while (j < n1){
System.out.println("Name of food item " + count + ":");
temp = keyboard.nextLine();
gerbilFood[j].setName(temp);
count++;
j++;
}
keyboard.nextInt() is only reading an integer from the keyboard, not reading the return character. So, when you first call keyboard.nextLine() you get the \n of the getInt().
Try this instead :
int n1 = keyboard.nextInt();
keyboard.nextLine();

Categories

Resources