How do I execute this Java Code that goes infinite loops? - java

public class Exercise3_10 {
public static void main(String[] args) {
int array[][] = new int[4][4]; // array는 4x4의 2차원 배열
int i;
boolean duplicate_index[] = new boolean[16];
for(i=0;i<16;i++) // duplicate_index 배열의 모든 원소에 false를 삽입
{
duplicate_index[i] = false;
}
for(i=0; i<10; i++)
{
int random_index = (int)Math.random()*15; // 0부터 15까지의 인덱스를 랜덤으로 뽑기
if(!duplicate_index[random_index]) // duplicate_index배열의 랜덤 인덱스의 원소가
{ // false라면 array배열에 랜덤숫자 부여 후 true로 변경
int random_number = (int)(Math.random()*10+1); // 1부터 10까지 랜덤 정수 뽑기
switch(random_index)
{
case 0: case 1: case 2: case 3:
array[0][random_index] = random_number;
duplicate_index[random_index] = true;
break;
case 4: case 5: case 6: case 7:
array[1][random_index - 4] = random_number;
duplicate_index[random_index] = true;
break;
case 8: case 9: case 10: case 11:
array[1][random_index - 8] = random_number;
duplicate_index[random_index] = true;
break;
case 12: case 13: case 14: case 15:
array[1][random_index - 12] = random_number;
duplicate_index[random_index] = true;
break;
}
}
else // true인 경우 현재 반복문을 한번 더 실행
{
i--;
continue;
}
}
for(i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
i want to make a two-dimentional array.
then, i need ten random numbers (range 1~10) in random index.
the rest of indexes are '0'.
i made a following code. but, this code didnt show any output in eclipse.
i think it goes infinite loop. but i dont know whats wrong.
i need your helps!!

Related

How to change UnicodeCategory in java?

I'm trying to migrate this C# code to Java.
Is there any possibility to migrate the unicodeCategory to a regex in Java, or is there a possibility to do the Unicode category by Java directly?
foreach (var currentChar in preNormalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(currentChar);
//https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Globalization.UnicodeCategory.LowercaseLetter);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6);k(DevLang-csharp)&rd=true
switch (unicodeCategory)
{
//case UnicodeCategory.NonSpacingMark:
//case UnicodeCategory.SpacingCombiningMark:
//case UnicodeCategory.EnclosingMark:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ParagraphSeparator:
if (!isPreviousSpaceChar)
builder.Append(" ");
isPreviousSpaceChar = true;
break;
case UnicodeCategory.Control:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.Format:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherNotAssigned:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.Surrogate:
// Caratères ignorés.
break;
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LetterNumber:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.TitlecaseLetter:
default:
builder.Append(currentChar);
isPreviousSpaceChar = false;
break;
}
}
var normalizedString = builder.ToString() ?? string.Empty;
normalizedString = normalizedString.ToUpper();
normalizedString = normalizedString.Trim();
return normalizedString;
There is a getType(char) that will return an int that you can then compare with a list of constants that are enumerated in the Java Docs.
Note that both C# code and the getType(char) are "wrong" because they don't support non-BMP characters (characters that use two char). But splitting a string in its "Rune" was a little more complex in C# until .NET Core 3.0.
public static String convert(String preNormalizedString) {
StringBuilder builder = new StringBuilder();
boolean isPreviousSpaceChar = false;
for (int i = 0; i < preNormalizedString.length(); i++) {
char currentChar = preNormalizedString.charAt(i);
int unicodeCategory = Character.getType(currentChar);
switch (unicodeCategory) {
case Character.DASH_PUNCTUATION:
case Character.CONNECTOR_PUNCTUATION:
//... You'll have to complete the list
if (!isPreviousSpaceChar)
builder.append(" ");
isPreviousSpaceChar = true;
break;
case Character.CONTROL:
case Character.CURRENCY_SYMBOL:
//... You'll have to complete the list
// Caratères ignorés.
break;
case Character.LOWERCASE_LETTER:
case Character.UPPERCASE_LETTER:
//... You'll have to complete the list
default:
builder.append(currentChar);
break;
}
}
String normalizedString = builder.toString();
normalizedString = normalizedString.toUpperCase();
normalizedString = normalizedString.trim();
return normalizedString;
}

Type of method in Java

Im new in Java and im trying this ex but it's giving me some problems with method's type of "primoGiorno":
I think it should be right ( "primoGiorno" takes int and return int) but it gives me error:
"This method must return a result of type int"; I cant understand why:
it returns, by switching "x": 0, 1, 2, etc.. that are int values. Where am I doing wrong?
import java.util.Scanner;
public class CheGiorno {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println ("Selezionare numero da 0 (Lunedì) a 6 (Domenica");
int inizioAnno = scanner.nextInt();
primoGiorno (inizioAnno);
scanner.close();
}
private static int primoGiorno (int x) {
switch (x) {
case 0 : return 0; break;
case 1 : return 1; break;
case 2 : return 2; break;
case 3 : return 3; break;
case 4 : return 4; break;
case 5 : return 5; break;
case 6 : return 6; break;
default : System.out.println ("Valore errato");
}
}
}
This line breaks it:
default : System.out.println ("Valore errato");
If it reaches the default value, it still must return an int value, which System.out.println ("Valore errato"); is clearly not.
A customary thing to have functions which return int do in the case of error is return -1.
Something like this:
private static int primoGiorno (int x) {
switch (x) {
case 0 : return 0; break;
case 1 : return 1; break;
case 2 : return 2; break;
case 3 : return 3; break;
case 4 : return 4; break;
case 5 : return 5; break;
case 6 : return 6; break;
default : return -1;
}
}
You can also remove the break; statements because return ends the function anyway.
In method "primoGiorno", the default case of switch statement if met, it returns nothing, but prints. Provide a return statement for default case with an int value.
Remove the break statements after return, it is unreachable code.

What is reason that two variables are the same, even should be different?

I'm trying to write plugin in minecraft (case opener). I have problem, because whenever variable current_item and variable next are the same, even should be different.
Inventory inv = Bukkit.createInventory(null, InventoryType.CHEST, "Losowanie");
ItemStack rnditem = new ItemStack(Material.STICK);
ItemStack current_item = new ItemStack(Material.APPLE);
ItemStack next = new ItemStack(Material.STICK);
for(int i = 0; i < 15; i++) {
Random rand = new Random();
switch(rand.nextInt(2)) {
case 0:
rnditem.setType(Material.DIAMOND);
break;
case 1:
rnditem.setType(Material.GOLDEN_APPLE);
break;
}
inv.clear();
current_item = next;
next = rnditem;
inv.setItem(13, current_item);
inv.setItem(14, next);
p.updateInventory();
Thread.sleep(i*100);
}
Different variables are being used to hold a shifting reference, but rnditem is never set to a new reference
switch(rand.nextInt(2)) {
case 0:
rnditem.setType(Material.DIAMOND);
break;
case 1:
rnditem.setType(Material.GOLDEN_APPLE);
break;
}
Should instead be
switch(rand.nextInt(2)) {
case 0:
rnditem = new ItemStack(Material.DIAMOND);
break;
case 1:
rnditem = new ItemStack(Material.GOLDEN_APPLE);
break;
}

Switch case for a group of inputs?

Given that I have the following finals:
private static final char CLIPPING_LOWER = 'c';
private static final char CLIPPING_UPPER = 'C';
private static final char RESET_LOWER = 'r';
private static final char RESET_UPPER = 'R';
private static final char LOAD_LOWER = 'l';
private static final char LOAD_UPPER = 'L';
private static final char QUIT_LOWER = 'q';
private static final char QUIT_UPPER = 'Q';
And consider the switch-case:
public void keyPressed(KeyEvent e)
{
char usersChoice = e.getKeyChar(); // get the user's choice
switch(usersChoice)
{
case LOAD_UPPER:
{
userPressedLoad();
break;
}
case LOAD_LOWER:
{
userPressedLoad();
break;
}
case RESET_LOWER:
{
userPressedReset();
break;
}
case RESET_UPPER:
{
userPressedReset();
break;
}
case CLIPPING_LOWER:
{
userPressedClipping();
break;
}
case CLIPPING_UPPER:
{
userPressedClipping();
break;
}
case QUIT_UPPER:
{
userPressedQuit();
break;
}
case QUIT_LOWER:
{
userPressedQuit();
break;
}
default:
break;
}
}
Is it possible to write a case for both c and C in one block (and also r and R ... etc) instead of writing a separate case for c and another case for C?
One solution to group the cases together
case LOAD_UPPER:
case LOAD_LOWER:
userPressedLoad();
break;
Another solution is to convert the input to uppercase and use only uppercase in switch statement
char usersChoice = Character.toUpperCase(e.getKeyChar());
case LOAD_UPPER:
userPressedLoad();
break;
You can user Character.toLowerCase with usersChoice, that way you don't have to handle 'R', 'C', etc.
http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#toLowerCase(char)
case CLIPPING_LOWER:
case CLIPPING_UPPER: {
userPressedClipping();
break;
}
Yes like this for instance:
case LOAD_UPPER: case LOAD_LOWER:
{
userPressedLoad();
break;
}

Object not updating when performing the switch statement in java

Not sure what I'm doing wrong here. But I want to change the card to the correct format.
For example given the card 1c change it to AC.
Here's some code I've been playing with:
public static void main(String[] args) {
String[] cards = {"1c", "13s"};
for (String card : cards) {
switch (card.toUpperCase()) {
case "1C":
card = card.toUpperCase().replace("1C", "AC");
break;
case "13S":
card = card.toUpperCase().replace("13S", "KS");
break;
default:
System.out.println(Arrays.toString(cards));
}
}
System.out.println(Arrays.toString(cards));
}
Any help would be great cheers.
Within the loop, card is just a local variable, and reassigning it doesn't modify the array cards. An immediate fix would be to index over the array so you can reference each element directly:
for (int i = 0; i < cards.length; i++) {
switch (cards[i].toUpperCase()) {
case "1C":
cards[i] = cards[i].toUpperCase().replace("1C", "AC");
break;
case "13S":
cards[i] = cards[i].toUpperCase().replace("13S", "KS");
break;
default:
System.out.println(Arrays.toString(cards));
}
}
Edit: to answer edhedges' comment, one would need to keep a counter variable outside the loop in order to keep using the enhanced-for syntax:
int i = 0;
for (String card : cards) {
switch (card.toUpperCase()) {
case "1C":
cards[i] = card.toUpperCase().replace("1C", "AC");
break;
case "13S":
cards[i] = card.toUpperCase().replace("13S", "KS");
break;
default:
System.out.println(Arrays.toString(cards));
}
i++;
}
Are you using Java 7? If you are not, you can't use Strings in cases.
See this problem and here(scroll down to Using Strings in switch Statements)
You can do this by the following code
public static void main(String[] args) {
String[] cards = {"1c", "13s"};
for (int i = 0 ; i < cards.length ; i++) {
switch (card[i].toUpperCase()) {
case "1C":
cards[i] = cards[i].toUpperCase().replace("1C", "AC");
break;
case "13S":
cards[i] = cards[i].toUpperCase().replace("13S", "KS");
break;
default:
System.out.println(Arrays.toString(cards));
}
}
System.out.println(Arrays.toString(cards));
}
In addition to #Paul Borella's answer I would say that this is only possible with Java 7. As Switch statement does not allow String as an expression. So you should get compilation error at line
switch(card.toUpperCase())
If you want to acheive the same functionality then you can go for Enum.
public enum Cards {
1C, 13S;
public String replacedString(){
case 1C : return "AC";
break;
case 13S : return "KS";
break;
default : return "";
}
}

Categories

Resources