Print the integers from 1 to a number given by user [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}

Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.

You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.

your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}

Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");

Related

ISBN Checker- No Loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to make a ISBN checker but it's not working. An example would be the user inputs 013601267 and return 0136012671. I'm not understanding what the problem is. No loops.
Any help would be great.
import java.util.*;
public class ISBN{
public static void main(String[]args){
Scanner in=new Scanner(System.in);
System.out.print("Enter 9 digit ISBN");
//variables//
int d1=in.nextInt();
int d2=in.nextInt();
int d3=in.nextInt();
int d4=in.nextInt();
int d5=in.nextInt();
int d6=in.nextInt();
int d7=in.nextInt();
int d8=in.nextInt();
int d9=in.nextInt();
int d10=(d1*1+d2*2+d3*3+d4*4+d5*5+d6*6+d7*7+d8*8+d9*9) %11;
//keyboard
if (d10==10){
System.out.print("ISBN"+d1+d2+d3+d4+d5+d6+d7+d8+d9+"X");}
else if(d10 !=10); {
System.out.print("ISBN"+d10);}
}
}
When someone enters their ISBN, are they entering it with spaces in between?
nextInt() will retrieve the integers separated by spaces, so it is likely that d1 is receiving the entire nine integers.
If you are entering them one at a time, then it should work.
Either enter the digits with spaces in between them, or each on their own line. Scanner will take care of the rest.
Note:
If you don't want the user to have to enter the digits one-by-one, try taking their input as:
String digits = in.nextLine();
You can reference each digit in that string with digits.charAt(0) etc.
int d1=Integer.parseInt("" + digits.charAt(0));
and so on. This will convert the single character digits.charAt(0) to your integer for the formula.
Hope this helps!

Program not running as intended [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make a java program that will add inputs until the total equals 100+ OR the user inputs 5 numbers. I'm also attempting to add a highest run to it that keeps track of the highest input. Currently it continues to run after 5 inputs when it's less than 100 total and my highest run doesn't work. How would I fix this?(I'm new to Java if you can tell)
import java.io.*;
public class HighScoreTest {
public static void main(String[] args) {
// input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// constant declarations
final Integer MAX = 100;
final Integer MAX_NUMBER = 4;
// variable declarations
String sName;
Integer currentTotal;
Integer currentNumber;
Integer numbersInputed = 0;
Integer count;
Integer maxRunToDate = 0;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("What is your name?");
// reading string from the stream
sName = reader.readLine();
currentTotal = 0;
for(count = 0; count < MAX_NUMBER; count++) {
numbersInputed += count;
}
do {
System.out.println("Please enter a number");
currentNumber = Integer.parseInt(reader.readLine());
currentTotal = currentTotal + currentNumber;
}while(currentTotal < MAX || numbersInputed == MAX_NUMBER);
if (maxRunToDate < currentTotal) {
maxRunToDate = currentTotal;
}
System.out.println(sName +", the total for this run is "+ currentTotal);
System.out.println("The highest run is "+ maxRunToDate);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
Some help to get you going:
currentRun = currentRun + currentNumber;
Simply doesn't make sense!
I assume that currentRun should count the number of runs so far. So that you can stop after the 5th round.
Thus: you should just increment that counter by for each round.
In other words: try to separate things. Step back and consider what kind of information you want to "track" and how many variables you really need to do that.
And please understand: we will not solve your assignment for you. If at all, there will be some guidance on how to make progress. But don't expect us to figure all the bugs in your code and resolve them for you.
There is several things that you need to know:
First, avoid wrap classes like Integer unless you intend to use it together with the Colection FrameWork or even Streams. If your problem is the fact that the output of the parsing is the Integer class, don't worry, for it will auto unbox. Something like this:
int currentNumber = Integer.parseInt(reader.readLine()); //Auto Unboxing
Second, why do you even have the for loop in the beginning? Remove it. If you want to initialize the numbersInputed variable just do it.
And third, if you whant to increment or decrement, you can just use ++ or `--
And check the Oracle Tutorials: https://docs.oracle.com/javase/tutorial/
I hope I have helped.
Have a nice day. :)

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

How to create a method that repeats a function?

Hello everyone I am new to the site and this is my first question from my Java programming class.
I have to create a program that asks a math question and tells the user if he is right or wrong, but the requirements also state that I need to create a method that generates a new question if the first question is correct, so when the computer asks what is 5 times 5 and the user inputs 25 the method should generate two new random numbers and ask the user for a result.
This is my code so far. I don't expect the answers as this is a school assignment but if anyone could give a direction it would be greatly appreciated it as this is my first java college course.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
}
while (answer != result);
}
I think you have the basic way that your loop statements work mixed up. A do statement is going to execute its block of code once and wont inherently loop on its own. A while loop will repeat until you tell it to stop. So without telling you exactly how to structure your assignment ;) you should look at those two things. But your code does compile and does do one run through of what you want it to do. So this means that the problem you have is in the logic aspect of your code. This means that the computer doesn't understand based on the structure of your code when to execute the sections of your code.
So my advice is to try writing it out in plain English first (pseudocode) that way you can work out how the logic of your program should run and then translate it into code. Sometimes just saying "I want x to happen when y. But I only want this to happen if event z has happened." can help you understand logical how something has to work.
Best of luck
You could add a while loop before the generation of the random numbers that would repeat until answer== "exit". Something along those lines would work fine
You should put a break; statement in the bottom else loop and put everything from your public static void declaration in an "infinite" for loop. When the user inputs an incorrect answer, the program will go to the else loop and break. Otherwise, it will keep on repeating in the "infinite" for loop. Here is a sample code showing what you could do.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
boolean loopTest = false;
while (loopTest= true)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from the user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
break;
}
while (answer != result);
}
}
}
*Note that the last } was not included in your program.

Identifing the single largest number occurring in a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's assume a text file is a Math text book. How should I code to find out the largest number in that file? I'm aware of using StringTokens, parseLong, split, etc. But I can't figure out a proper way to combine them.
To be precise, let's say that text has something like:
Chapter 3.5
Million has 6 zeros. Ex. 6,000,000
Billion has 9 zeros. Ex. 9,000,000,000
Trillion has 12 zeros. Ex. 8,000,000,000,000
The largest number is 8000000000000. How do I extract that?
Thanks in advance.
Use the Scanner interface. This code assumes you pass in the file path as the first argument. The Scanner interface handles commas in numbers. I use BigInteger to handle any size number.
public static void main (String[] args) throws java.lang.Exception
{
BigInteger biggestNumber = null;
Scanner s = new Scanner(new FileReader(args[0]));
while( s.hasNext() ){
if( s.hasNextBigInteger() ){
BigInteger number = s.nextBigInteger();
if( biggestNumber == null || number.compareTo(biggestNumber) == 1 ){
biggestNumber = number;
}
}
else {
s.next();
}
}
System.out.println("Biggest Number: " + biggestNumber.toString());
}
You can play with an online example at: http://ideone.com/zKI5rM . It doesn't read from a file but uses a string in the code instead.
One place this would fail is if the book splits large numbers across lines. I'm not sure what your source material is, but that is something to keep in mind.
Store the largest number seen so far (initially, negative infinity), then go through the entire file extracting each number and if it's greater than the largest number you've stored, store it. At the end, the number stored is the largest number. Use double rather than long to account for very large numbers and noninteger numbers. The simple way to find all integers is to use a Scanner, feeding next() into parseDouble(...) and comparing anything that doesn't throw a NumberFormatException.
The easiest way would be to parse the text file line by line.
You can do this using regular expressions to see if you have any number formats located in the current line. If you do then you can check to see if it's larger than the previously found number.
Here is an excellent tutorial on regular expressions if you haven't came across them yet.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can use BigInteger
public class Test {
public static void main(String[] arg) {
String line = "215,485,454,648,464";
String line1 = "5,454,546,545,645";
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger(line.replaceAll(",", "")));
list.add(new BigInteger(line1.replaceAll(",", "")));
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
}
Output: largest: 215485454648464
For your situation
public static void main(String[] args){
Scanner input = new Scanner(new File("yourFile.txt");
List<BigInteger> list = new ArrayList<BigInteger>();
while (input.hasNextLine()){
String line = input.nextLine();
String[] tokens = line.split("\\s+");
String number = token[5].trim(); // gets only the last part of String
list.add(new BigInteger(line.replaceAll(",", "")));
}
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}

Categories