scanner + loop single line - java

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

Related

Java Scanner Class ( System.in)

I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.

Calling a method that displays the output pattern only

I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!

How to print txt file with file numbers using I/O?

i am printing a .txt file using the Scanner and I want to print the file with line numbers. here is my code. My problem is that the line numbers aren't incrementing.
import java.util.*;
import java.io.*;
public class List
{
public static void main(String[] args) throws IOException
{
int line =1;
File f = new File("src/List.txt");
Scanner sc = new Scanner(f);
while(sc.hasNext())
{
int num = 1;
System.out.print(num);
System.out.println(sc.nextLine());
num++;
}
}
}
Output:
1Bird
1Dog
1Cat
1Elephant
1Tiger
1Zebra
Expected Output:
1 Bird
2 Dog
3 Cat
4 Elephant
5 Tiger
6 Zebra
Take int num = 1 and place it out side of the loop...
int num = 1;
while(sc.hasNext())
{
System.out.print(num);
System.out.print(" "); // Separate the line number from the text
System.out.println(sc.nextLine());
num++;
}
This way it won't be reset every time the loop restarts...
Your bug seems to be mixing up line and num in the body of the loop, but I would also recommend you use formatted output and something like -
while(sc.hasNextLine()) {
System.out.printf("%d %s%n", line++, sc.nextLine());
}
The format String "%d %s%n" describes a number then a space then a String and then new-line. Next, perform a post-increment on line. Finally, get the nextLine() from the Scanner.
You should remove
int num = 1;
because this will ALWAYS set num BACK TO 1 while it hasNext. This is why the line number won't increment.
After deleting that, also delete
num++;
because there is no more num variable. Replace that with:
line++;
I hope this helps!

integer value read from System.in is not the value typed

I am a newbie to Java, and as an exercise wanted to WAP a simple program to print required no. of '*' characters according to the user. But somehow, the output of this code always remains similar:
package stars;
public class Stars {
public static void main(String[] args) {
int no_stars=0;
try {
System.out.print("Enter the number of stars:");
no_stars = (int)System.in.read();
} catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n){
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}
}
If I replace '*' with i, I can see that it loops upto 50/52/54, even though i run the loop no_stars times.
What seems to be the problem here?
You need to parse the number received from System.in.read() or alternatively read it as an integer, currently you just cast it, so if you enter 5, it passes 0x35 times (which is the value of the character '5')
You can do, for example:
Scanner scan = new Scanner( System.in );
printstars( scan.nextInt() );
Because you are reading ASCII code of the character from input here:
no_stars = (int)System.in.read();
It should be
no_stars = Integer.parseInt(Console.readLine());
There are two mistakes in your code.
First
System.in.read()
Is reading a byte, not a integer, so, it is parsing the integer and getting the first byte of it.
Second
for (i = 0; i <= n; i++) {
will print always one star more than requested.
So, it should be changed to
for (i = 0; i < n; i++) {
Suggestion: You could use Scanner to read your integer, for example
Scanner scanner = new Scanner(System.in);
no_stars = scanner.nextInt();
no_stars = (int)System.in.read();
This is using the ASCII value of whatever character the user enters. Try this instead:
no_stars = System.in.read() - '0';
Or, remove the no_stars variable all together,
printstars(System.in.read() - '0');
Also, in your for-loop, the condition should be i < n, in order to perform the correct number of iterations. And there's no need to declare i outside of the loop, you can just do for (int i = 0; i < n; i++).
Here is the corrected program for you: (the main problem was this line //no_stars = (int)System.in.read();)
public static void main(String[] args) {
int no_stars=0;
try{
System.out.print("Enter the number of stars:");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
no_stars = Integer.parseInt(name);
//no_stars = (int)System.in.read();
}
catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n)
{System.out.println(n);
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}

Categories

Resources