Print a string a number of times in a row - java

Ok so i know there is a smilier question but I think mine is slightly different so I'll post and risk getting panned by you all ;)
So i want the user to input a word (Java) and then input a number (4) and the programme then prints in this case JavaJavaJavaJava
Here is what I have got so far
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
System.out.println(str);
System.out.println(num);
From what i understand i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer but hey.
Any help massively appreciated :)

You have to use a for-loop for this, and scan the number as an integer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
System.out.print("Enter a number: ");
int num = sc.nextInt();
for (int i=0;i<num;i++) {
System.out.println(str);
}
}

Nearly there. Add the following at the end:
int number = Integer.parseInt(num);
for (int i=0; i<number; i++) {
System.out.print(str);
}

There are a couple things you're going to want to change to do this.
1) You're only calling System.out.println(str); once, so the string will only be printed once. Now, you could just put System.out.println(str); 3 times, but then you'd be stuck with num always being 3. What I'd suggest is using a for loop, like the one found here. Basically, it would look like this assuming num is 10 and str is test string
for(int i=0;i<10;i++)
{
System.out.println("test string");
}
You'll want to change that to fit your exact case, but that should be enough to get you started.
2) You're right here
i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer.
You want to scan it in as an integer, otherwise it's useless for your purposes. For all java knows, you want to print out your string puppy or bacon times rather than 3 or 4.
If you still have any questions about this, lemme know. We've all been there man.

Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
int counter = 0;
while (counter < num){
System.out.print(str);
counter ++;
}

Related

Exiting from while loop not working in java

I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}

How can I fix string matrix index problem?

I'm trying to store name and address of persons in the form of 2d array, but when I run my code it accepts less values only. For example if I give the array 2 rows and 2 columns, it accepts only 3 values.
I've tried searching on other forums, couldn't get the proper answer.
I also changed the dimension values but it gives wrong result only.
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
You read 4 values but one is an empty line from when you press enter for int addr=scan.nextInt();
A quick fix is to read that empty line
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
---> scan.nextLine();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
Edit:
Or you can use scanner.skip Skip newline character while reading from Scanner class
In addition to the other answer here is how your code should look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int iPeople = scanner.nextInt();
System.out.print("Enter the number of address: ");
int iAdresses =scanner.nextInt();
scanner.nextLine();
String data[][] = new String[iPeople][iAdresses];
for(int i=0; i < iPeople; i++)
{
for(int j=0; j < iAdresses; j++)
{
System.out.printf("Enter %d address for person %d:%n", j + 1, i + 1);
data[i][j] = scanner.nextLine();
}
}
And try to follow these conventions:
Use proper Java naming conventions
Make your code more readable by providing appropriate empty lines between lines you feel are too cluttered or belong to different groups based on what operation are they trying to accomplish.
If you want to understand why, the behavior of nextLine is explain here : Java Scanner doesn't wait for user input
You can also replace nextLine by next to avoid this.

How can I get input validation with Java using Scanner with regex.Pattern and arrays

I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.
This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?
Here is the relevant chunk of code from my little app.
//These variables used during input validation
String tempName;
int tempGrade;
//These regex patterns are for input validation
//Names can be 1-15 letters and grades are 2 digits
Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
Pattern gradePattern = Pattern.compile("[0-9]{2,2}");
//Parallel arrays to hold last names and grades
String[] names = new String[5];
int[] grades = new int[5];
Scanner in = new Scanner(System.in);
try {
for(int i = 0; i<5; i++) {
System.out.println("Enter a name:");
tempName = in.nextLine();
System.out.println("Enter a grade:");
tempGrade = in.nextInt();
in.nextLine();
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
}
names[i] = tempName;
grades[i] = tempGrade;
}
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
tempName = in.nextLine(); //<-- add this.
}
Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.

Using BufferReader to get input from User

So when I run my program's main method it prints:
Enter number of test cases:
1
Enter string 1
Enter string 2
rat apple cat ear cat apple rat
For some reason it prints Enter string 1 and Enter string 2 before I even put in anything for String one. Can anyone shed any light as to why this is happening. Is there something wrong with the way I have the BufferReader setup?
Code:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int testcases = in.read();
System.out.println("Enter string 1");
String[] str1 = in.readLine().split(" ");
System.out.println("\nEnter string 2");
String[] str2 = in.readLine().split(" ");
for(int i = 0; i < testcases; i++)
{
String result = lcss(str1, str2);
System.out.println("\nLCSS: "+ result);
System.out.println("\nLCSS Length = "+ result.length());
}
}
Please use the following.
int testcases = Integer.valueOf(in.readLine());
Read more on BufferedReader.read()
int testcases = in.read(); doesn't read the line break (when you press Enter).
The readLine() in the line String[] str1 = in.readLine().split(" "); will now begin to read directly after the number you entered and search for the next line break. The line break from you entering the number is now found and the function directly returns without waiting for your input.
So much for the explanation on what causes your program to behave the way it does.
Now you do have another error, as BufferedReader.read() doesn't do what you think it does. Check the documentation
So when you enter a 1 your testcases varaible will contain the UTF-16 value of the character '1' which is 31.
As other answers already pointed out you should either use Integer.valueOf(in.readLine()); to get the value for testcases or use Scanner
EDIT:
Get the number of test cases as integer
Create a 2 dimensional array to store test cases. First dimension holds each test case & second dimension holds String[] of word list in each test case.
Iterate through "for loop" until you get each test case string array for total number of test cases,
Sample code:
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int testcases = in.nextInt();
System.out.println("test cases:"+testcases);
String[][] strs = new String[testcases][];
for ( int i =0; i< testcases ; i++ ){
System.out.println("Enter string:"+i);
in = new Scanner(System.in);
if (in.hasNext()) {
String s = in.nextLine();
System.out.println(s);
strs[i] = s.split(" ");
System.out.println("Length:"+strs[i].length);
}
System.out.println();
}
// Add your logic
}

Why can't I enter another string after the first time in a for loop?

I want to create a program that allows me to enter name, age, and year of birth for 5 different people. However, I get a problem where I cannot enter another name after I entered the first in my for loop. Here is my code:
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
}
}
The program works fine when I run it, but it will not allow me to enter the other 4 names after I entered the first. Here is the output I am getting:
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
names[i] = keyboard.next();
Take a look- I've fixed your code- added "keyboard.nextLine();" at the end.
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
keyboard.nextLine();
}
}
The reason you need to add it is that "nextInt()" will only read what you've entered and not the rest of the line. What's left of the line will be then read by "names[i] = keyboard.nextLine();" automatically.
By putting another "keyboard.nextLine()" at the end, I've skipped what left of the line and then "names[i] = keyboard.nextLine();" gets a new line to read input from.
Every beginner in Java encounters this problem sooner or later :)

Categories