Why doesn't the following program work? [closed] - java

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
I can't figure out why the following program doesn't work. Please help me where did I make a mistake. Thank you.
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int[] numbers = new int[100];
int largestNumber = 0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
}
}

This part:
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
makes no sense. You:
test if the next thing in the input is an integer;
attempt to parse ten next tokens, assuming that they are all integers;
at the eleventh token you check whether it's another integer or "finish";
throw an exception if it's neither;
repeat everything if it's not "finish".
What you should actually do is something much, much simpler:
check next token:
if it's "finish", you're done;
if it's an integer, parse it;
otherwise throw error;
repeat this for up to 100 times;
you are done accepting input. Proceed to processing it.

I think that Scanner is unnessecarily complicated and doesn't work to much of the time. Here's how to do it the old fashioned way:
public class LargestNumber {
public static void main(String[] args) {
int largestNumber=0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while (!(line = r.readLine()).equals("finish")) {
int val = Integer.parseInt(line);
if (val > largestNumber)
largestNumber = val;
}
System.out.println("The largest number is: " + largestNumber);
}
}
For this, enter each number on a new line. I used a shorter algorithm here, which is to read one number, and if it is bigger than the maximum so far, the new number is the maximum so far

According to the doc:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So i thing you could do this instead:
int counter = 0;
while (counter < numbers.length) {
if (sc.hasNextInt()) {
numbers[counter++] = sc.nextInt();
} else {
if (sc.hasNext("finish")) {
sc.close();
break;
} else {
System.out.println("It's neither number nor 'finish'.");
sc.next();
}
}
}
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
hope that helps

Related

how can i check if the number is perfect square by not using math.sqrt

i want to make a program which related to this question:
An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.
I did built something goes like:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
So it doesn’t give what i want when i run it. What should i change or add ?
I think your for loop interpretation might be wrong, I made up something that might just work. Give this code a try.. You can make the method return a boolean too if you want.
static void perfectSquare(int number) {
for (int i = 1; i < i * number; ++i) {
// 'i' is the divisor, making sure
// it is equal to the quotient
if ((number % i == 0) && (number / i == i)) {
System.out.println(i);
}
}
If you want to brute force every number then you are on the right track but you should only print "Not ok" if all numbers in the loop have failed otherwise you may have a perfect square but "Ok" will be hidden within many "Not ok" lines. Also there is nothing in your for loop so the if statement always checks if 0*0 == num.
This looks like it may be a homework question so I won't give a full answer for you but think about how you can make this more efficient.
If you have found an integer number that matches do you need to keep going?
Do you need to check every number? (a starting point may be following the principles of a binary search)
I ended up like this:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
int b = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){
if (a*a == num){
b = 1;
break;
}
}
if(b==1){
System.out.println("Perfect Square");
}
else {
System.out.println("Not ok");
}
}
}
Thanks for support !

How to check if userInput is an int [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 2 years ago.
Improve this question
I am trying to output "Invalid value" if the MAX_VALUE I have is not an integer. Whenever I run this code, my overall output gets changed. I am wondering how to correctly do this.
import java.util.*;
public class ForLoopPractice {
public static void main(String[]args) {
Scanner scnr = new Scanner(System.in);
final int MAX_VALUE;
System.out.println("Print even values");
System.out.print("Max value: ");
MAX_VALUE = scnr.nextInt();
for (int i=0; i < MAX_VALUE; i++) {
if (i % 2 == 0) {
System.out.println(i + " ");
}
}
while (!scnr.hasNextInt()) {
System.out.println("Invalid value");
scnr.next();
}
System.out.println();
System.out.println("Print a range of values");
System.out.print("First Value: ");
int firstVal = scnr.nextInt();
System.out.print("Last Value: ");
int secondVal = scnr.nextInt();
for (int i = firstVal; i >= secondVal; i--) {
System.out.println(i+ " ");
}
for (int i = firstVal; i <= secondVal; i++) {
System.out.println(i+ " ");
}
}
}
Use a Try-Catch block. Scanner.nextInt() throws InputMismatchException if the input isn't a number.
You can use a function to make sure the program doesn't go forward until the user has selected the proper input.
public static int getValidNumber(){
try{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num;
num = sc.nextInt();
return num;
} catch (InputMismatchException ex){
System.out.println("Invalid Input.");
return getValidNumber();
}
}
You could wrap "MAX_VALUE = scnr.nextInt();" with:
if (scnr.hasNextInt())
It will return true if the next value can be interpreted as an integer.
While taking the input, you can check it by a method isDigit().
If N is a input given by user, check it by System.out.print(Character.isDigit('N'));
The method will provide boolean value.

Creating a random output from an user input array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

Not able to take user input when using while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code bellow which is supposed to take a user input and store it in an array, and I was just wondering why it is not allowing me to input any numbers.
Should the input part be inside the if statement? Also what is the best way to make it work properly?
import java.util.*;
public class fun_with_loops {
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
int numberSize = 0;
System.out.print("Enter a few numbers please\n");
while (numbers.length < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
}
}
Problem
The following expression on loop's control is always evaluated as false:
while (numbers.length < 10)
since array's length is in fact equals 10 as when declared.
Solution
In order to program work as expected you have to use numberSize variable as control:
while (numberSize < 10)
since it grows based on number of inputs.
As Am_I_Helpful stated, you are using a while loop on a value that will not change. I am not sure if the use while is needed in this case. Since you want to loop a specific amount of times you might want to use a for loop. If the amount of times will depend on the size of your array, you could still replace the "10" by your array length (numbers.length).
for (int i; i< 10; i++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
Hoping it helped!
Dan
a short and sweet summary of when to use each loop:
http://mathbits.com/MathBits/CompSci/looping/whichloop.htm
but of course it always depends of your goal while coding so it's sometimes hard to say which is best if you are not the one coding.
Because the array is initialized to size 10, the length will always be 10. A counter variable needs to be used. Here is the code:
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
System.out.print("Enter a few numbers please\n");
int count = 0;
while (count < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[count] = input;
count++;
}
else
{
break;
}
}
The length property returns the size of the array, not the number of elements that are present in the array. You need to keep track of number of elements in the array on your own.
for(int eleCount = 0; eleCount < 10; eleCount++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[eleCount] = input;
}
else
{
break;
}
}

Java: What is wrong with this code? [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 7 years ago.
Improve this question
I'm trying to print out the sum of each individual number in a number but it is not giving the correct answer. What is wrong with my code?
import javax.swing.*;
public class Tallist {
public static void main(String[]args) {
int sum = 0;
String tal = JOptionPane.showInputDialog(null, "skriv ett tal");
for(int X = 0; X<=15; X++) {
sum += tal.charAt(X);
System.out.println(sum);
}
}
}
First of all, if you want to iterate through the entire string, you should not fix the number of iterations to 15 in your for-loop.
for(int X = 0; X<=15; X++)
Could be written as:
for(int x=0; x<tal.length(); x++) //user lower case for non-final variables
Next, you are summing up the ASCII value of the input string, not the numbers.
So if "123" was input into the InputDialog, you are summing up ASCII for 123: (49 + 50 + 51) instead of adding up (1+2+3).
Just convert it to integers before summing up:
sum += Character.getNumericValue(tal.charAt(x));
If I understood you correctly you want to calculate the crossfoot of a number.
Here the code you need with user input via input dialog:
public class Crossfoot
{
public static void main(String[] args)
{
while (true)
{
String userInput = JOptionPane.showInputDialog("Enter number:");
if (!isInteger(userInput))
{
continue;
}
int crossfoot = 0;
for (int i = 0; i < userInput.length(); i++)
{
crossfoot += Character.getNumericValue(userInput.charAt(i));
}
System.out.println(crossfoot);
}
}
public static boolean isInteger(String string)
{
try
{
Integer.parseInt(string);
return true;
} catch (NumberFormatException numberFormatException)
{
return false;
}
}
}
As another user already wrote, you should iterate over the whole string and be careful with the ASCII values of the characters.

Categories