This is my assignment:
Write a program where the user enters a string, and the program echoes it to the monitor with one character per line:
C:\>java LinePerChar
Enter a string:
Octopus
O
c
t
o
p
u
s
I have tried, but I'm getting some compilation errors. Here's my code:
import java.util.*;
class CharactorEcho{
public static void main(String args []){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string :");
try {
String inputString = sc.nextLine();
for(int i=0; i < sc.length(); i++) {
char c = inputString.charAt(i);
System.out.println("" + c);
}
} catch(IOException e) {
}
}
}
In your loop, you should be looping over the length of the String that you get from the Scanner.nextLine, not the scanner itself.
for(int i=0; i<inputString.length(); i++){
If you want the input to be echoed with each character on the same line, use System.out.print instead of println.
Two Issues:
Change for(int i=0; i<sc.length(); i++){ to for(int i=0; i<inputString.length(); i++){
You care comparing against the scanner and not the input string.
Also, please try catching
java.util.NoSuchElementException
java.lang.IllegalStateException
in place of IOException, as your statement sc.nextLine() with throws NoSuchElementException and IllegalStateException, not IOException.
Make sure you add the related import statements.
You need to import IOException. Add this line to the top of your code, just after the package line if you have one:
import java.io.IOException;
Also, you're asking sc for a length instead of the string, so change your for to this:
for(int i = 0; i < inputString.length(); i++) {
Really though, you shouldn't be catching IOException. In fact, your code will never throw an exception. This is really all you need:
public static void main(String args []){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string :");
String inputString = sc.nextLine();
for(int i=0; i < sc.length(); i++) {
char c = inputString.charAt(i);
System.out.println("" + c);
}
}
Calling nextLine on a Scanner made with System.in will only throw an exception if System.in isn't accessible, and it won't even be an IOException, so don't worry about it.
One final observation, you don't need to do "" + c in your println. System.out has a println method specifically for char, so you can just call:
System.out.println(c);
Related
Ask the user to enter in a number, then you can print out the number of many * on the screen without spaces or newlines. You may use your Scanner object in numbers 5, 6 and 9 also.
Input:
7
Output:
*******
I can do this but I can't do it in a single line all the astericks
import java.util.Scanner;
class {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.println("*");
}
}
}
You can use a for-loop like so changing println to just print so you print the * on the same line:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number:");
int inputNumber = sc.nextInt();
for(int i=0;i<inputNumber;i++) {
System.out.print('*');
}
}
}
Try it here!
Note: You can initialize i within the for-loop and don't need to declare it beforehand
It's my first response i hope to help you...
Try
System.out.print("*");
if you use
System.out.println("*");
Your program will do a line jump...
To print all the asterisks in a single line, use print instead of println:
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.print("*"); // <- note the difference here!
}
Why? Let's look at the docs:
print(String):
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
So println(String) calls print(String) then println(). What does println() do?
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
Now you see the difference! println(String) prints a new line after it prints the string while print(String) does not!
Here's a cleaned up version of your code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int x = scan.nextInt();
for (int i = 0; i < x; i++) {
System.out.print("*");
}
You should to use
System.out.print("*");
and not
System.out.println("*");
Because println return to line and print not.
Hope this can help you.
Note
Your class need a name in your question you do :
class {
and this wrong in java, so you need to declare your class like this:
class nameClass {
//Your code
}
Take a look here :
Getting Started
and here:
Arrays
I am very new to java and this community. I am looking for someone to possibly be able to explain why my code is going into an infinite loop. I believe it has something to do with my while loop. The program compiles but when I enter a phrase i want for my acronym builder to create the program dosent do anything, it just blinks at the next line. When i press ctrl c to exit, it then shows the acronym.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
while (input.hasNext() )
{
phraseToChange = input.next();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The problem is not truly caused by your while loop but because the fact that scanner will keep asking user new input (system.in stream will always open) until EOF. Therefore, the problem can be solve using StringTokenizer if it's allowed by your professor. Down here is the code example
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
boolean phraseToChange2 = true;
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String nextLine = input.nextLine();
StringTokenizer st = new StringTokenizer(nextLine, " ");
while (st.hasMoreTokens())
{
phraseToChange = st.nextToken();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
System.out.println("reach here");
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The reason of why your loop never ends it the fact that System.in stream is always open. You should change the condition to while (!phraseToChange.equals("exit")) or something. Then the user will be able to finish the input by sending "exit" string to your program.
If you don't have to use a while loop with input.hasNext() you can use this. May want to clean up where necessary, but I believe this does what you want.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym {
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char[100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0; i < wordCounter; i++) {
System.out.print(acroynmArray[i]);
}
}
}
Sample build output:
run:
This program builds acronyms
Enter a phrase:
Google Rocks Socks
GRSBUILD SUCCESSFUL (total time: 4 seconds)
Code snippet that causes the change:
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
Alternatively you could use this:
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String line = input.nextLine(); // Obtain user entered line
acroynmArray[0] = line.charAt(0); // First letter is known; set it
wordCounter++; // increment wordCounter
//Loop the characters in the retrieved line
for(int i = 0; i < line.length(); i++){
// If it's whitespace then we know the next character must be the letter we want
if(Character.isWhitespace(line.charAt(i))){
acroynmArray[wordCounter] = line.charAt(i+1); // Set it
wordCounter++;
}
}
But as Tom said in my deleted post, this is quite fragile code. It works, until it doesn't, as in it wouldn't take much to break it as it doesn't handle trailing and starting whitespaces
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
Scanner sv=new Scanner(System.in);
b=sv.nextInt();
Scanner st=new Scanner(System.in);
n=st.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
}
I tried using scanner class but it is not executed by eclipse as it only shows sc,sv and st objects of scanner class is resource leaked and never closed.
Well, it appears you have some configs that keep your program from compiling and running based on the resource leaking (not an Eclipse user). Your code compiles and runs with Intellij on my machine so you have a few choices.
Change your configuration to ignore the warning/error. (not recommended)
Close the one Scanner you need. (scanner.close()) You can get more than one value from the single scanner. So, ditch the other ones.
To accomplish (2) another way you could use try-with-resources block and it will be closed automatically at the end of the try.
try (Scanner sc = new Scanner(System.in)) {
// put your code to get input here
} catch (IOException ioe) { ... }
In addition to the scanner issues you're asking about, you have a significant error in your code that will make it impossible to get any meaningful/accurate output. Consider...
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
int result = a + c;
System.out.print(result + " ");
}
c is made anew on each loop and assigned a value of 0 and so c = 2 * c * b; will equal 0 always; and a + c will then always just equal a.
Dont need to create a new Scanner Object...
just do:
int a, b, n;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
final int result = a + c;
System.out.print(result + " ");
}
I was typing this out when #Xoce was posting his answer, so it's exactly the same as his :)
The only other thing that I'd like to add is that if you're using IntelliJ, try pressing control-alt-i to auto-indent your code.
public static void main(String[] args) {
//Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
n=sc.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
I am suppose to read in a text document (I/O) and display the number and the number of asterisks as the number. So "5 1 3" would display as:
5*****
1*
3***
My code displays the output as "5*****1*3***". I have tried a number of things but cannot figure it out.
My code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class HWK1B {
public static void main(String[] args) throws IOException {
File file = new File("data.txt");
Scanner inFile = new Scanner(file);
while (inFile.hasNext()) {
int num;
num = inFile.nextInt();
System.out.print(num);
for (int i = 0; i < num; i++) {
System.out.print("*");
}
}
inFile.close();
}
}
Add System.out.println() at the end of your main loop and it will go the next line.
while(inFile.hasNext())
{
int num;
num = inFile.nextInt();
System.out.print(num);
for(int i=0; i < num; i++)
{
System.out.print("*");
}
System.out.println();
}
To start a new line, you need a "newline character" so that the display knows to separate the lines. One way is to manually add a newline character, which is denoted by "\n".
The second way is to generate your string all at once (so you build the string "5*****" instead of printing it one character at a time), and then printing it using the "println" (or print line) command.
The first way is a bit more efficient as well as easier to work into your existing code.
An easy way to solve this is by simply adding System.out.println() (or two by the look of your example) after you added the astericks.
import java.io.*;
import java.util.Scanner;
public class HWK1B
{
public static void main(String[] args) throws IOException
{
File file = new File("data.txt");
Scanner inFile = new Scanner(file);
while(inFile.hasNext())
{
int num;
num = inFile.nextInt();
System.out.print(num);
for(int i=0; i < num; i++)
{
System.out.print("*");
}
System.out.println();
System.out.println();
}
inFile.close();
}
}
If you changed System.out.print(num) to System.out.println(num), a new line would be added before the asterisks resulting in an example such as:
5
*****1
*3***
If you changed System.out.print("*") to System.out.println("*"), a new line would be added every time an asterick is added resulting in:
5*
*
*
*
*
1*3*
*
*
You never do a linebreak, so the console prints it out all in a row.
To insert a linebreak you can use e.g. the System.out.println() method.
This code should give you 2 linebreaks after each number:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("data.txt");
Scanner inFile = new Scanner(file);
while(inFile.hasNext()) {
int num;
num = inFile.nextInt();
System.out.print(num);
for(int i=0; i < num; i++) {
System.out.print("*");
}
System.out.println();
System.out.println();
}
inFile.close();
}
Following is the question for prime number generator problem (from spoj.com):
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input :
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output :
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example :
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Following is my code for the same:
package competitivecoding;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
int t = sc.nextInt(); // inputs the "no." of lines that users want to enter
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[2];
for(int i=0; i<t; i++){
line[i] =st.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
System.out.println();
}
}
}
Error: The code when submitted, produces RuntimeException on spoj.com, although it works completely fine on my system.
package abc;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[10];
for(int i=0; i<t; i++){
line[i] =sc.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");}
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
}
}
//try this
Always handle the exception that can be raised (ideally, any exceptional behaviour that you can recover from, accoding to the Oracle documentation for Exception) and never consider user input as safe:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = 2;
try {
/* for each line */
for (int i = 0; i < t; i++) {
/* read the line */
String line = br.readLine();
/* split the line */
String[] numbers = line.split(" ");
if (numbers.length != 2)
throw new ArrayIndexOutOfBoundsException();
/* parse values */
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
/* do your check */
__find_prime_numbers__
}
}
catch (NumberFormatException ex) {
/* notice the user -> input format isn't correct, for example: "1 m" */
}
catch (ArrayIndexOutOfBoundsException ex) {
/* notice the user -> input format isn't correct, for example: "1 " or "1 2 3" */
}
It works for me. Print the error so we have more info.
You can also do Scanner.nextInt().
Things like multiple spaces , tabs can mess stuff
Are you using sc.nextInt() before the first sc.nextLine()? because if that's the case, you could have a '\n' character in the buffer after using it. So when you use nextLine() for the first time, you actually get the '\n' character instead of the next line. And when you try to parse to integer it fails.
See here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
If this is the case, the solution is simple. Just fire a call sc.nextLine() that does nothing except to 'eat' that character from the buffer.