Inifnite loop while reading numbers - java

Basically I am trying to write a program that will read a finite set of values from the user then print the average. (I know how to do the calculations so I will leave those out.)
I am having a problem with the logic side of the loop.
I understand that everyone here would prefer that I attempted it but I am new to loops and I am having extreme difficulties understanding loop logic.
I am attempting to do this assignment for my class but the teacher is flying through material and does not help at all when questions are asked. When I ask for help with a problem he says do your best to attempt it and I will grade it accordingly?
I honestly do not know where to start.
import java.util.Scanner;
public class P4Point5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String Status = "";
int count = 0;
while (in.hasNext()) {
count++;
}
for (int i = 0; i < count; i++) {
//Do calculations here?
}
}
}

You never get the next element:
while (in.hasNext())
count++;
You are always on the 1st element and asking if there is a 2nd element.
You should use:
while (in.hasNext())
int next = sc.nextInt();
BTW: please avoid statement without curly brackets. It is the root of all evil.

When you read for the first time, you don't read anymore, so hasNext() will stay always true since there will always be next element, which is.. the current element you're reading.
One solution is to do something like that:
String input = null;
while((input = in.next()) != null) {
//...
}

You can try this:
while (in.nextInt() != 'SOME INT TO STOP LOOP')
count++;
Instead of verify every time if we have an entered number, we can verify if the entered number is an stop condition.

Related

Sudoku Code Program - Checking Rows,Columns, and Boxes

I need help checking rows, columns, and boxes for a Sudoku program. I am a high school student that needs help completing this project. If any one could provide help that would be awesome! I am currently working on checking boxes where I have a comment saying "Start Here". Thanks!
import java.util.*;
public class Run
{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
char [][] board = new char [9][9];
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Sudoku!\n");
fill(board);
printBoard(board);
inputLengthandDigits(board);
System.out.println();
printBoard(board);
}
public static void fill(char[][] arr){
for(int row = 0; row < arr.length; row++){
for(int col= 0; col< arr[row].length; col++){
arr[row][col] = '-';
}
}
}
public static void printBoard(char [][] array)
{
for(char[] row: array)
{
for(char play: row)
{
System.out.print(play+ " ");
}
System.out.println();
}
}
public static void inputLengthandDigits(char[][] array){
Scanner in = new Scanner(System.in);
for (int i = 0; i < 9; i++)
{
System.out.println("\nEnter the numbers in row " + (i+1) + ":");
String input = in.nextLine();
String numbers = "123456789-";
boolean numberscheck = false;
boolean endCheck = true;
boolean onlyOnce = true;
//Input Validation Starts Here!
//Checks if Input is only digits 0-9
do{
if(endCheck==false){
System.out.println("\nPlease input numbers only (1-9)!");
input = in.nextLine();
}
if(onlyOnce==false){
System.out.println("\nPlease input numbers only once!");
input = in.nextLine();
}
//Checks Length of User Input
while(input.length() < 9 || input.length() > 9){
System.out.println("\nPlease input 9 numbers!");
input = in.nextLine();
}
//Start Here
for(int a = 0; a<input.length()-1; a++){
for(int b= a + 1; b<input.length(); b++){
if(input.charAt(a)==input.charAt(b)){
onlyOnce = false;
}
}
}
for(int x = 0; x < input.length(); x++){
char thing = input.charAt(x);
numberscheck = false;
for(int y = 0; y < numbers.length(); y++){
char numbersn = numbers.charAt(y);
if(thing == numbersn){
numberscheck = true;
endCheck = true;
break;
}
}
if(numberscheck == false){
endCheck = false;
break;
}
}
}while(endCheck==false || onlyOnce==false);
for(int j=0; j<9; j++){
array[i][j] = input.charAt(j);
}
}
}
}
My initial response is too long for a comment. I'm not sure I have a solution to your problem, largely because you haven't actually pointed out which bit is a problem yet, but these pointers should help improve things anyway:
Please reformat your code. It is actually quite painful to look at. Spaces should be used consistently around variables, key words, brackets and operands. Opening curly braces should be on the same line as the method signature, for() loop or whatever else comes first. You have random blank lines within methods which don't separate logical sections so are just confusing. The compiler won't care about any of this, but if you can make your code look neater people will instinctively presume you care and are more likely to credit you with the ability to write decent code.
You have declared a new scanner variable three times. This is redundant and wasteful clutter. Either have a single, class-wide scanner, or (preferably), only create a scanner in a method which actually uses it and then remember to call scanner.close() once the scanner is no longer required.
inputLengthandDigits is a weird name. Is 'Lengthand' a single word, or should it be 'inputLengtHandDigits' or 'inputLengthAndDigits'? In camel case, capitalise every word except the first to make the whole easier to read. Whatever it should be, I don't understand from the name what this method does. It isn't inputting anything, it's getting inputs from someone else. Perhaps getData or populateGrid might be more explanatory.
9 appears quite a few times, with no explanation. I know where it came from, because I spend far too much time playing Sudoku, but it is a magic number and these are to be avoided at all costs. I met a magic number in the workplace once, wasted half a day trying to do what could have been a ten minute job if colleagues had recorded what the number was and where it came from. Here, just have a private static final int maxNumber = 9; statement.
A good thing: your main() method has almost no fiddly details in it. You have effectively used method calls to tell a story and describe what is happening elsewhere. This is a really, really good thing to do :)
Some of your logic tests can be tidied up a bit, e.g. !onlyOnce is the same as onlyOnce == false, and input.length() < maxNumber || input.length() > maxNumber can be simplified to input.length() != maxNumber. It's exactly the same logic, but faster to type and easier to read :)
It looks like your code under the //Start here comment is checking that you don't have any duplicate numbers. If you do get duplicate numbers, the program is still going to try and run the next bit of code before asking the user for alternative input. Is that something you want to happen, or a waste of time?
I actually burst out laughing when I saw a variable called 'thing'. Please, find a name which actually describes the purpose of this variable.
I have now run the code, and it rightly pointed out an error when I tried to key in duplicate numbers for row 4. However, it's now stuck there and keeps asking me to try again even when I put in a valid set of digits. This needs to be fixed. Look closely at which flags are triggering the request to retry. Run your code in debugging mode (you are using an IDE like IntelliJ or Eclipse, aren't you?) and deliberately enter a bad row to see the behaviour for yourself and where the logic is going wrong.
This whole method to get the row input, validate it, and then populate the array, is very big and confusing. You need to refactor it into a lot of smaller methods. Here is a suggestion to play with:
private static char[][] populateGrid(char[][] array) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i <maxNumber; i++) {
String rowData = getRowInput(scanner);
populateRow(array, rowNumber, rowData);
}
scanner.close;
return array;
}
private static String getRowInput(Scanner scanner) {
System.out.println("\nEnter the numbers in row " + (i + 1) + ":");
String input = scanner.nextLine();
while (!isValidInput(input) {
System.out.println("Please enter only the digits 1-9 in any order, with no duplicates or omissions");
input = scanner.nextLine();
}
return input;
}
private static boolean isValidInput(String input) {
if (!rightLengthOfInput(input)) {
return false;
}
if (!allUniqueDigits(input)) {
return false;
}
if (!usesCorrectCharacters(input)) {
return false;
}
return true;
}
I'll leave you to make the different input validation methods. It will largely be a case of moving your existing code, but the method names will help humans understand what each section is doing. This structure also allows you to cleanly add more validation checks, should such a thing be desired in the future.
Things to consider after all that:
Are you going to check that you have a viable Sudoku solution, or will you trust the user to put in correct data such that the columns also have each of the nine digits in them? How will you handle an invalid grid, e.g. each row is identical?
How far does this assignment want you to go? Do you need to systematically remove numbers to get a solvable puzzle rather than a completed grid? Will the assignment stop at a puzzle which can be seen in the console, or do you need a printable format, or will the user be able to play through the program? If the latter option, will this be in the console or using a graphical interface?
I appreciate that there is a lot to think about and work on here. Take it steadily, one step at a time, and keep asking questions if you need too.

A method that I wrote with a scanner class doesn't seem to end

I wrote a method in order to get the choice of the user for the size of a grid. However, my code doesn't seem to work after executing the method, as it continues to run without end after I type in the response to console (if it matters, I am on repl.it). What is the issue with the code that prevents it from ending?
public static String createSize() {
int count = 0;
String answer = "";
Scanner sc = new Scanner(System.in);
System.out.println("How big do you want the grid? (Sizes: 4x4, 5x5, 6x6)");
String size = sc.nextLine();
//Checks if user-inputted answer matches possible answers
while (count < 1) {
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = sc.nextLine();
}
else {
System.out.println("That was not a viable size. Please type a viable size.");
size = sc.nextLine();
}
}
sc.close();
return answer;
}
In the first If check in the while loop
Change
answer = sc.nextLine();
to
answer = size;
since u do not want the user to input size twice.
Your code should work fine now.
Let me know if anything isn't clear so I can modify and elaborate further
what's the main problem? I tried to run this code on all possible test cases and I didn't get any problem.
In the if statement you have answer = sc.nextLine(); which will again ask you for the input that's why the program was not executing further. If you pass input second time only then it will execute. Further in if statement answer wasn't assigned any value so even after entering two values it will not return anything.
Correction :-
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = size;
}

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

Entering Same number twice in an array

Any possible way to keep entering numbers, and when the same number is entered 2 or more times an error message arises or something like that? I need this to be answered in Java only. I'm new and I don't know where to go from here. I need help searching values in the array and then printing out all the numbers that have been entered.
public class Test
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How big is the group?: ");
int[] group = new int[input.nextInt()];
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
group[i] = input.nextInt();
}
I think this is what you're looking for. Inside of the for loop, there's a while loop spinning to keep collecting new ints until you enter one that's not already in the list.
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
int next = input.nextInt();
while(Arrays.asList(group).contains(next)) { // Keep asking for new input while the input is already in list
System.out.println("That number is already in the group ... try again.");
next = input.nextInt();
}
group[i] = next;
}
Since this is clearly a "learning exercise", it is only appropriate to give you hints:
You can search an array by stepping through the array indexes and testing the elements at each index.
A method and a class both need a closing } ...
I need this to be answered in Java only.
That is incorrect. What you REALLY need is some hints. If we give you Java code, you miss out on the important learning experience of writing it yourself. And THAT is the WHOLE POINT of the homework. Go ask your teacher if you don't believe me.

Using a while loop in an ArrayList

I'm new to programming and to this website, so here goes.
I wanted to write a program that would allow as many input strings as possible to be added to an ArrayList. So I used a while loop in the following code. What I intended was for the loop to break if the input was 0.
import java.util.*;
public class AddToList2
{
static Scanner q = new Scanner(System.in);
public static void main(String[] args)
{
ArrayList<String> inputlist = new ArrayList<String>();
while (true)
{
System.out.print("Enter something here: ");
String x = q.nextLine();
inputlist.add(x);
if (x.equals("0"));
break;
}
}
The program was compiled without error, but sadly, when I ran the program many times, the loop broke no matter what the input was. Any way to solve this?
Well, that was careless of me! Anyway, I had created that program in order to find out what was wrong with this:
ArrayList<String> endangeredlist = new ArrayList<String>();
ArrayList<Integer> popn = new ArrayList<Integer>();
while (true)
{
System.out.print("Name an animal: ");
String animal = q.nextLine();
endangeredlist.add(animal);
if (animal.equals("EXTERMINATE"))
break;
q.next();
System.out.print("How many are left in the wild? ");
int numberleft = q.nextInt();
popn.add(new Integer(numberleft));
}
(This is part of a much larger program.) My intention was for the loop to break when the animal name input was EXTERMINATE. Sadly the program throws a NoSuchElement exception if the input first time round was EXTERMINATE, and if I had inputted something else first the loop would start, but then inputting EXTERMINATE second time round does not break the loop. Why is that?
You have an extraneous semicolon after your if, which effectively makes it
if (x.equals("0")) { }
break;
You have a semi-colon at the end of your condition.
This turns the break into a statement of its own, without the condition.
Your if statement is broken
if (x.equals("0"));
This is basically saying if (x.equals("0")) do nothing...
This is one of the reasons why you should use parenthesis around your if statements
if (x.equals("0")) {
break;
}

Categories

Resources