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();
}
Related
This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.
RightTriangle.java: Write code that reads in a number R from the user, and displays a figure with R rows of "$" characters as the following pattern. For instance, if the user enters a 4 for R, your program should display:
$$$$
$$$
$$
$
Heres my code currently.
import java.util.Scanner;
public class RightTriangle {
public static void main(String[] args) {
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt($);
System.out.println(R);
}
}
You could solve this task like so:
import java.util.Scanner;
public class triangle{
public static void main(String[] args){
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt();
int k = R;
for(int i=0; i<R; i++){
for(int j=k; j>0; j--){
System.out.print('$');
}
k = k - 1;
System.out.print('\n');
}
}
}
We use two for loops. The first for loop is used to print a newline after the nested for loop printed the correct amount of $ for that line. Note how we decrease the value of the inner loop counter inside the outer for loop to decrease the amount of $ printed each line.
Use a descending for-loop with the input as the index.
In each iteration, print the $ symbol i times. You could do this using a loop or using another way.
EDIT:
import java.util.Scanner;
public class RightTriangle {
public static void main(String[] args) {
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt(10);
for (int i = R; i >0; i--) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append("$");
}
System.out.println(sb.toString());
}
}
}
A little late, but here it is anyway :)
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
I'm trying to create an array with user input from a dialog box. It's supposed to ask how many numbers the user wants to enter, then ask the user to input the numbers. The code is then supposed to output the numbers in reverse order. Below is the code I have so far.. it doesn't work. I did something wrong with trying to initialize the array with user input. I'm pretty new to java so any advice is welcome. Thanks in advance.
public static void main(String[] args)
{
String input;
int space;
double [] numbers;
double count;
String numberInput;
double number;
input = JOptionPane.showInputDialog
(null, "How many numbers would you like to enter?");
space = Integer.parseInt(input);
numbers = new double[space];
count = 0;
while (count < space)
{
numberInput = JOptionPane.showInputDialog
(null, "Enter a number to be sorted: ");
number = Double.parseDouble(numberInput);
for (int i = 0; i < numbers.length; i++)
numbers[i] = number;
count++;
}
double[] numbers2 = swapArray(numbers);
JOptionPane.showMessageDialog(null, numbers2);
}
public static double[] swapArray(double[] array)
{
double[] result = new double[array.length];
for (int i = 0, j = result.length - 1;
i < array.length; i++, j--)
{
result[j] = array[i];
}
return result;
}
}
Here is my take on your assignment. It should give you some ideas on how to deal with the problem, without giving you a copy-paste solution, nor the best-possible (to my own ability) structure/logic (but still giving you tips to point you in their direction):
package so_q33405148;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
//TIP: You can use 'Scanner' instead of a 'Reader' here, to avoid having to parse strings into ints (scanner can do it for you)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many numbers would you like to enter?");
int count = Integer.parseInt(br.readLine());
int input[] = new int[count];
for (int i = 0; i < count; i++) {
System.out.print("Enter a number to be sorted: ");
//TIP: With some clever math, you can invert the array right as it's still filling up here, by manipulating a new int (so 'i' is unchanged, as it's the for-loop's index) using 'i' and 'input.length'...Or, with a little creativity and insight, you may even achieve the same result manipulating 'i' directly somewhere else...
input[i] = Integer.parseInt(br.readLine());
}
System.out.println("Original array:\n" + Arrays.toString(input));
//TIP: Better methods to reverse arrays and/or collections exist.
//Take a look at SO question #3962766 (puritan solution without as much memory-footprint) and also Google about 'Arrays.asList()' and 'Collections.reverse()' (learn about collections-sorting)
int reversedInput[] = new int[input.length];
for (int i = 0; i < count; i++) {
reversedInput[i] = input[count - i - 1];
}
System.out.println("Reversed array:\n" + Arrays.toString(reversedInput));
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
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.