I am required to create a method that prompts user to input three words and then it has to store the data in an array. The method should then print the three lines in reverse so for example word OVER would come out as REVO.
I have got it done sort of however I don't know how to get the other 2 lines to work. As it is, only the first user input gets reversed.
Here is the code so far;
import java.io.*;
public class Average {
public static void main (String[] args) throws IOException {
BufferedReader getit;
getit = new BufferedReader
(new InputStreamReader (System.in));
System.out.println ("Enter first line:");
System.out.flush ();
String text = getit.readLine();
while (true) {
System.out.println (reverse(text));
System.out.println("Enter 2nd line:");
System.out.flush ();
text = getit.readLine();
System.out.println("Enter 3rd line:");
System.out.flush ();
text = getit.readLine();
System.out.println("Finish");
break;
}
}
public static String reverse (String original) {
String reversed = "";
int pos = original.length() - 1;
while (pos >= 0) {
reversed = reversed + original.charAt(pos);
pos -= 1;
}
return reversed;
}
}
You called the function reverse just once. Try to call it every time you get a string.
What you are doing is, You took the first string as input and your program went into an loop near while(true) you printed the reverse of the string. You took two more strings.
Where are you reversing them? and the break at the end of the loop doesn't make sense.
you may remove the while loop and break and add call the reverse function. I am not writing any code as you could do it easily.
Write System.out.println (reverse(text)); after text = getit.readLine(); each time.
Related
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
Language: Java.
Aim:
Boolean Array gridA[] should become true on whatever index is read from input (i.e. if input is "init_start 2 4 5 init_end" then gridA[] indexes 2,4 and 5 should become true). That much I managed to get working but I have two problems:
input:
init_start int int int int int (...) int init_end
for example: init_start 2 6 12 init_end
Problems:
any integer from input that exceeds the value of (instance variable) int L (which determines the index-length of the array) should be ignored, to prevent integers from outside the domain of Array gridA[] from having influence.
Using if(scanner.nextInt != L){} didn't seem to work.
I also need this method, or the body of the method to start when input begins with "init_start" and stop when input ends with "init_end".
How do write code so that it can read both String and integers from the same input?
I meant to do this using
if(scanner.Next=="init_start") followed by
a = scanner.NextInt; which, as I suspected, didn't work.
Attempts at solving:
After googling I tried putting String initialInputStart in a Scanner:
localScanner(initialInputStart);
but I failed to get that working. Other information I found suggested I'd close and reopen the scanner but I need the information to be read from a single line of input so I doubt that will help.
code:
java.util.Arrays.fill(gridA,false);
java.util.Arrays.fill(gridB,false);
String initialInput;
String initialInputStart;
int a;
int i;//only for testing
i = 0;//only for testing
System.out.println("type integers"); //only for testing
while( scanner.hasNextInt() && i<5){ //I can't find a way to make loop stop without missing input so I'm using i temporarily
a = scanner.nextInt();
gridA[a] = true;
System.out.print(a);
System.out.print(gridA[a]+" ");
i++;
}//end while
I wrote a little program which pretty much does what you described as your aim; I read line by line and split each into tokens I further process. The tokens describe what the data means/what state we are in. The actual data is parsed in the default: case in the switch(token) block and branches in behaviour from state to state (which is merely visible here as we only have two states: "init" and "not init", beside the keywords):
public static void main(String[] args) {
int L = 13; // not sure if this is needed
boolean[] gridA = new boolean[L];
Reader source;
/**
* from file:
* source = new FileReader("grid.csv");
*/
/**
* from classpath resource:
* source = new InputStreamReader(MyClass.class.getResourceAsStream("grid.csv"));
*/
/**
* from string:
* source = new StringReader("init_start 2 6 12 init_end");
*/
/**
* from std-in:
* source = new InputStreamReader(System.in);
*/
try(BufferedReader stream = new BufferedReader(source)) {
boolean init = false;
// loop
input_loop:
while(true) {
// read next line
String line = stream.readLine();
if(line == null) {
// end of stream reached
break;
}
if(line.trim().isEmpty()) {
// ignore empty lines
continue;
}
String[] tokens = line.split(" ");
for (String token : tokens) {
switch (token) {
// evaluate keywords
case "init_start":
init = true;
break;
case "init_end":
init = false;
break;
// for input from console
case "exit":
break input_loop;
default:
// parse input, based on state (expand "init" to an enum for more states)
if(init) {
// read init input
int index = Integer.parseInt(token);
if(index >= 0 && index < gridA.length) {
gridA[index] = true;
} else {
throw new RuntimeException("illegal grid index: " + index);
}
} else {
// read undefined input
throw new RuntimeException("unrecognized token: " + token);
}
break;
}
}
}
} catch(IOException ex) {
throw new RuntimeException("an i/o exception has occurred", ex);
}
System.out.println(Arrays.toString(gridA));
}
" How do write code so that it can read both String and integers from the same input?"
do you want to have an Input like this: "123, foo"
if thats the case use:
String input = scanner.nextLine();
String[] parts = input.split(",");//" " to split it at an empty space
String part1 = parts[0]; // 123
int Number = Integer.parseInt(part1) // you could inline it, but i chose this version for better refference
String part2 = parts[1]; //foo
if your Input looks like this "123 or foo"
you have to read the input as String and check the String afterwards if its a Number:
String input = scanner.nextLine();
if (text.contains("[a-zA-Z]+") == false){ //looks if the input does NOT contain any characters
int nummber = Integer.parseInt(input);
} else{
String text = input;
}
afterward you can compare your text:
For the first mentioned case:
if("init_start".equals(parts[1])){ //*
yourMethod();
}
For the other case:
if("init_start".equals(text)){ //*
yourMethod();
}
*Also:
"I meant to do this using if(scanner.Next=="init_start")"
*Very important! To compare Objects, such as String use .equals(). "==" only works on primitive types
Edit: I've read your example. You could go with a combination of my solutions. split the string at space(" ") and check parts[x] if it is an integer. But i wouldnt recommend this method! Why dont you split your input in three parts: init_start would start your function. After that your method would expect an input of Integers like "int int int" after you inserted the Integers your function could automatically stop or wait for the input "init_stop". That seems to me more reasonable. If you want to go with the single line solution you can evaluate the number of your int's by get tingparts[].lenght()-2
use this implementation:
public static void main(String args[]){
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter a line");
String dat = in.readLine();
System.out.println(dat);
}
catch(IOException e){
System.out.println("IO ERROR !!!");
System.exit(-1);
}
}
I am trying to use a while condition where if a user inputs a string with the first character as number 1, the loop should end. However, in my case the loop never ends. What could I be doing wrong?
public static void main(String[] args) {
ArrayList<Integer> instructions = new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
String input = "";
String termIns = input.substring(0);
// int termInsInt= Integer.parseInt(termIns);
do {
input = keyboard.nextLine();
int inputInt = Integer.parseInt(input);
instructions.add(inputInt);
//String termIns = input.substring(0);
} while(!termIns.equals("1"));
In addition, what would display the list of all elements in the ArrayList?
You need to update termIns with the user input in each iteration of loop:
do {
input = keyboard.nextLine();
int inputInt = Integer.parseInt(input);
instructions.add(inputInt);
termIns = input.substring(0);
} while(!termIns.equals("1"));
Also substring(0) will not help you as
substring(int beginIndex)
Returns a new string that is a substring of
this string. The substring begins with the character at the specified
index and extends to the end of this string.
You can use startsWith method instead directly on input as mentioned here
while(!input.startsWith("1"))
you're not updating termsIn which is part of your terminating condition.
Also, you can display all the elements in the Arraylist by creating a loop outside of your do-while that prints out all the elements in your arraylist. I'd take a look at the javadoc on Arraylist.
I am required to pass a scanner as a parameter to a method and have the method print things based on what was passed with the scanner.
So, if the scanner passed contains "6 fox 3 bees 2 25 8 ducks"
The method would print out
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
I have no problem writing the method. I'm just confused as to how I would use a scanner to do that.
Well, a Scanner is used for reading stuff in from either a file or standard input (System.in). Passing it around wouldn't do you a whole lot of good unless you want to encapsulate functionality and responsibilities.
If we think about this from a problem-solving stance, what are we really trying to get?
We have a string that contains first a number and a string, and the second string could contain numerals.
All of these symbols are separated by space.
Everything is contained on one line; we don't have to worry about moving to the next line.
It's entirely up to you how you want to approach this, but a couple of suggestions are as follows:
Since you know the precise order of tokens, you can make multiple calls to Scanner.next() and Scanner.nextInt().
while(scanner.hasNext()) {
System.out.println(readFromScanner(scanner));
}
scanner.close(); // DO NOT DO THIS if you are using System.in!
public static String readFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
int times = scanner.nextInt();
String phrase = scanner.next();
for(int i = 0; i < times; i++) {
result.append(phrase);
}
return result.toString();
}
You could also read the entire line in at once using nextLine(), and parse it using String.split(), which gives you numerals at every even index (0, 2, 4, etc), and strings at every odd index (1, 3, 5, etc).
You can read from the Scanner using methods like next() and nextInt(). You can read the full Scanner javadoc here.
Try this. There are two ways of reading input.
1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5
Refer to this article. This will solve your problem.
http://www.mkyong.com/java/how-to-read-input-from-console-java/
You can pass a Parameter by :
Input Accept here
System.out.println("Input here: " );
String input = scan.next();
// This how you gonna pass the parameter
inputedByScanner(input);
Your Method Accept it and print the inputed value.
public void print inputedByScanner(String input){
System.out.println(input);
}
public class Homework {
public static void main(String[] args) {
System.out.println("Enter something:");
doStupidHomework(new Scanner(System.in));
}
private static void doStupidHomework(Scanner scanner) {
int i = 0, x = 0;
for (String next = scanner.next(); next != null; next = scanner.next(), i++) {
if (i % 2 == 0) {
x = Integer.parseInt(next);
continue;
}
for (int j = 0; j < x; j++) {
System.out.print(next);
}
System.out.println();
}
}
}
Output:
Enter something:
6 fox 3 bees 2 25 8 ducks
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}