It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
So i'm working on a bowling calculator assignment that takes a series of inputs and calculates a score. The test input provided by my instructor has a number of test cases which denote how many strings will need to be computed to scores. The problem I am having is that I am not able to get all 3 strings (there are 3 test cases) into a single string, separated on different lines.
This is what the input is:
3
--,--,--,--,--,--,--,--,--,--
X,X,X,X,X,X,X,X,X,XXX
X,13,X,81,5/,X,18,33,X,X36
I am trying to get it to be formatted as such:
--,--,--,--,--,--,--,--,--,--
X,X,X,X,X,X,X,X,X,XXX
X,13,X,81,5/,X,18,33,X,X36
However, when I run my code I get this as the output:
--,--,--,--,--,--,--,--,--,--
X,X,X,X,X,X,X,X,X,XXX
X,13,X,81,5/,X,18,33,X,X36
Here is what I've got so far.
import java.io.*;
import java.util.*;
public class Bowling {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("input.txt");
Scanner scanFile = new Scanner(inFile);
int tc = scanFile.nextInt();
String N = "";
for (int i=0; i < tc; i++)
N += scanFile.next();
System.out.println(N);
}
}
**UPDATE: Thank you everyone for the answers, I have learned quite a bit because of your responses. At the time of asking this question I was tied up on this problem and was not thinking straight. I looked over my code again and realized all i had to do was add this line before the strings were added to the variable:
N += "\n";
Again, thanks to all those who commented.
I recommend using a StringBuilder if you are going to be concating a lot of String's. But on every iteration of the loop, you can append a newline character:
StringBuilder sb = new StringBuilder();
for (int i=0; i < tc; i++) {
sb.append(scanFile.next());
sb.append("\n");
}
System.out.println(sb);
It is possible to:
• Make a String[] array
• Use dividers, like \t
• Use other methods
Also, don't forget to say that you want us to tell you how to use newline characters.
I'd love to use StringJoiner in your case,I totally agree with #GBlodgett's answer. But this too can serve as an alternate.
From the javadoc,
StringJoiner is used to construct a sequence of characters separated
by a delimiter
which exactly suits your case. Your loop reads as,
StringJoiner sj= new StringJoiner("\n"); // Here, "\n" is the delimiter between every join.
for (int i=0; i < tc; i++){
sj.add(scanFile.next());
}
System.out.println(sj.toString());
Also, this avoids appending unnecessary newline after the last appended line.
I've found a bug in your code that explains why the output is in one line.
The command System.out.println(N) should be inside the for loop.
The variable N is unnecessary - please omit it.
There is another problem of resource leakage in your code, because the Scanner was never closed. The scanner should be closed using the auto closeable mechanism (by using try with resource statement).
I propose the following code to solve the problem:
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("input.txt");
try (Scanner sc = new Scanner(inFile)){
int tc = sc.nextInt();
for (int i=0; i < tc; i++) {
System.out.println(sc.next());
}
}
}
There are multiple strings being passed to this program from standard input. The first int input T, is the number of test cases(Strings) being passed to this program. A string which has different alternate characters is perfect. If alternate characters are the same, you have need to delete 1 of those two characters. Basically, you have to count, how many characters, do you need to delete to get a perfect String? For example: ABABAB is pefect while AABABAA is not perfect. You need to delete 2 A's, the first one and the last one.In AAAA, you need to delete 3 A's to get a perfect string. String input can be very large. What is the fastest way to count number of such deletion? The code below, written by me, is working very slow.
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int T= scan.nextInt();
String str;
int count=0;
for(int i=0; i<T; i++){
str=scan.next();
for(int j=0; j<str.length()-1; j++){
if(str.charAt(j)!=str.charAt(j+1)){
j+=2;
}
else{
count++;
}
}
System.out.println(count);
}
}
Before you worry about the performance, worry about whether your solution is correct. For the input ABAAB, your program returns 0, however 1 A must be removed to obtain a perfect string.
Then: what do you mean with "very large". How many characters is that? And what is "very slow"?
You will have to look at every character of the string at least once, so you will not get much faster. However, you might be able to optimize a bit. At the moment, it is possible that you look at a single character twice (once in str.charAt(j+1) and in the next iteration in str.charAt(j)). It is certainly possible to write your algorithm in such a way that every character of the string is visited exactly once. But again, you should focus on correctness before you focus on speed.
This is my working code after eliminating all the logical errors. For some test cases its execution time is up to 0.45-0.50 seconds. Can its performance be improved?
public static void main(String[] args) {
int T=0; String str;
Scanner sc = new Scanner(System.in);
T=sc.nextInt();
for(int i=0; i<T; i++){
str= sc.next();
solve(str);
}
}
public static void solve(String str){
char first, second; int count=0;
for(int i=0; i<str.length()-1; i++){
first= str.charAt(i);
second= str.charAt(i+1);
if(first==second){
count++;
}
}
System.out.println(count);
}
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
For an assignment I have due, my group and I were asked to code an educational/interactive game, and we decided on a basic maths one.
To get the users answers, we decided to use Java Scanner and put this line of code at the top of all the code we have;
java.util.Scanner
One of the loops that use this is the page with the questions on it, the loop looking something like this;
scoreCount = 0;
for (questions = 0; questions < 5;) {
//get the user's answer
userAnswer[questions] = input.nextInt();
//text box for users answer
if (userAnswer[questions] == compAnswer) {
//put tick next to answer
//add one to score
scoreCount = scoreCount + 1;
} else if (userAnswer[questions] != compAnswer) {
//put cross next to answer
}
//go to next question
questions++ ;
}
I'm working through all the errors that were thrown up and every time i don't have java.util.Scanner commented out Processing throws us the errors unexpected token: and then either class or void, which i don't get, but when java.util.Scanner is commented out, the classes and voids all work and the .input.nextInt() isn't recognised.
I am new to Java programming and Processing, any help at all would be greatly appreciated
EDIT
i think this is the link which lets you see my code, it's called Test;
https://github.com/MeganSime/Week8DataVis
you have to check if scanner has next int (token)
Scanner input = new Scanner(System.in);
.
.
if(input.hasNextInt()) { // or hasNext()
userAnswer[questions] = input.nextInt();
}
You're probably inserting a non int value where the scanner expects that. You should do something like that:
if(input.hasNextInt()) {
userAnswer[questions] = input.nextInt();
} else {
scan.next(); //consume any non-int value like ":"
}