loop based on user input java - java

I want to write a program that queries the user for a "number n" and then output the word repetition n times.
For example the word is "Hello".
So far I've got this:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Zahl 1:");
int number = scanner.nextInt();
}
Which should end in this ->
Number: 3
Hello
Hello
Hell
.
I don't know how to move forward.
I thank you for your time in advance!

You can use functional programming.
IntStream.range(0, n)
.forEach(System.out.println(variable));
Here n is the number of times that string is to be printed and a variable is a string.

This code out print "Hallo" n times (n = numbers)
String s = "Hello";
for (int i = 0; i < number; i++){
System.out.println(s);
}

Related

What is the best way to take input as per testcases?

I want to take input as per this way. The input begins with number of testcases x and in each of the next x lines there are two numbers m and n.
For eg:-
2
1 10
3 5
But i want to call a function after taking the input. I want to pass the input values to the function to print my output . I tried this way but it is calling the function first.
Basically i want to take all inputs first then call the function for each test case for getting the output.
Below is the code what i tried.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
for(int i=0 ; i<x ; i++) {
int n = in.nextInt();
int m = in.nextInt();
PrimeFactors(n , m);
System.out.println();
}
}
You should call function after loop.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int[][] array = new int[x][2];
for(int i=0 ; i<x ; i++) {
array[i][0] = in.nextInt();
array[i][1] = in.nextInt();
}
for (int[] ints : array) {
PrimeFactors(ints[0], ints[1]);
}
}
I suggest you to split the input and the algorithm.
You can just extract PrimeFactors(n , m); to a separate class and test in via regular unit tests.

Unable to take input from console in java

I am new to Java and facing problem while taking input from the console.
Here's my code:
import java.util.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
System.out.println(t);
for (int n = 0; n < t; n++) {
for (int i=0;i<4;i++){
int mzeroes = sc.nextInt();
int nones = sc.nextInt();
int stringLength = sc.nextInt();
String string=sc.nextLine();
System.out.println(mzeroes);
System.out.println(nones);
System.out.println(stringLength);
System.out.println(string);
}
}
}
}
Input:
2
2 2 8 11101000
3 4 16 0110111000011111
Error:
Exception in thread "main" java.util.InputMismatchException: For input string: "0110111000011111"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at solution.main(solution.java:13)
I tried the same code but there were no errors and it executed successfully. I think you are making the mistake while giving the input. This is how the input has to be given :
As the first input is two so it will ask for two inputs in the loop and then when you pass the first input for the loop it will print out the there 3 ints one after other and the remaining string at the end. And the same goes for the second input of the loop.
Note: The String string = sc.nextLine(); will give you the string so space before the last number will also be taken in the string.
Hope this helps.

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Java Input method not terminating

I'm trying to work out this problem:
Input
The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
Output
For each number Ai from the last one till the first one you should output its square root. Each square root should be printed in a separate line with at least four digits after decimal point.
Sample:
input:
1427 0
876652098643267843
5276538
output:
2297.0716
936297014.1164
0.0000
37.7757
And here's my code:
public class ReverseRoot
{//start class
public static void main(String[] args)
{//start main
Scanner in = new Scanner(System.in);
ArrayList<Long> array = new ArrayList<Long>();
array.add(in.nextLong());
while(in.hasNextLong())
{
array.add(in.nextLong());
}
in.close();
for (int i = array.size(); i > 0; i--)
System.out.printf("%.4f%n", Math.sqrt((double)array.get(i)));
}//end main
}//end class
Anybody know what the deal is?
Your for loop doesn't work because you try to access non existing elements in your list.
Change the loop to this:
for (int i = array.size() - 1; i >= 0; i--)
System.out.printf("%.4f%n", Math.sqrt((double)array.get(i)));
}
Why do you have array.add(in.nextLong()); outside the loop? You can delete this.
To exit your input just type any non-long character into your console.
As I observer, we should have 2 loops. The first loop is for 'multiple lines' and the second loop is for 'multiple long value' of a single line.
Here is an example
public static void main(String[] args) throws Exception {
Scanner console = new Scanner(System.in);
Scanner lineTokenizer;
// this is to handle all 'lines'
while (console.hasNextLine()) {
String lineContent = console.nextLine();
if (lineContent == null || lineContent.isEmpty()) {
// this is to exit the program if there is no input anymore
break;
}
lineTokenizer = new Scanner(lineContent);
// this is to handle a 'line'
while (lineTokenizer.hasNext()) {
if (lineTokenizer.hasNext()) {
long number = lineTokenizer.nextLong(); // consume the valid token
System.out.printf("%.4f%n", Math.sqrt((double) number));
}
}
lineTokenizer.close(); // discard this line
}
console.close(); // discard lines.
}

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
}

Categories